为了账号安全,请及时绑定邮箱和手机立即绑定

.htaccess 的多个重写规则,重定向到 www,同时包含 index.php

.htaccess 的多个重写规则,重定向到 www,同时包含 index.php

PHP
慕妹3242003 2023-09-22 16:33:31
具体来说,我想将所有非 www 页面重定向到 www,同时还运行位于我的根目录中的 index.php 文件。为了解决这两个问题,我正在使用.htaccess.我已经将我的站点设置为运行 PHP 文件以在每个目录中运行。但是当我添加从非 www 到 www 的重定向时,它就中断了。问题似乎是多个重写规则相互冲突。其中一个运行而另一个不运行,或者站点仅响应 500 错误。我的问题是,是否应该将多个重写规则“组合”为一个?或者我只是错误地使用了这些多个规则?(或者这只是我搞砸的一些奇怪的语法?我已经研究这个有一段时间了哈哈)很感谢任何形式的帮助。<IfModule mod_rewrite.c>RewriteEngine OnRewriteBase /RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php  [L,QSA]# Redirect to www.RewriteCond %{HTTP_HOST} ^example.com$RewriteRule (.*) https://www.example.com/$1 [R=301,L] </IfModule>
查看完整描述

2 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

我发现这个有效:


RewriteEngine On

RewriteBase /

RewriteRule ^index\.php$ - [L] #if not already index.php


RewriteCond %{REQUEST_FILENAME} !-f #only if NOT a FILE (directory / non-existent file)

RewriteRule . /index.php [L] #redirect to index.php


RewriteCond %{HTTP_HOST} ^example.com$

RewriteRule ^(.*) https://www.example.com/%{REQUEST_FILENAME} [R=301,L] #redirect to https://www

</IfModule>

这不可能像所写的那样“工作”,因为存在许多错误:

  • 您缺少打开<IfModule mod_rewrite.c>指令。然而,无论如何,这个<IfModule>包装都不是必需的,应该被删除。

  • Apache 不支持行结束注释。具体来说,以下行将由于“错误的标志分隔符”而导致 500 错误:

     RewriteCond %{REQUEST_FILENAME} !-f #only if NOT a FILE (directory / non-existent file)

    更新:如果您在此处没有看到 500 错误响应,则您可能使用的是 LiteSpeed 服务器;而不是 Apache?在 LiteSpeed 上,此行尾注释似乎按预期工作!)

  • www除了对目录(包括根目录)或真实文件(除了index.php)的请求之外,重定向到的外部重定向(最后)永远不会被处理。在现有重写之前,需要先进行此重定向。然而,请看下一点......

  • 您在目标 URL 中错误地使用了REQUEST_FILENAME(绝对文件系统路径) - 这将导致格式错误的重定向。您可以使用REQUEST_URI服务器变量(完整的 URL 路径),但请注意,您还存在双斜杠问题。因此,它需要像下面这样重写:

     RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

小要点:

  • RewriteBase这里没有使用它,可以安全地删除。(除非你有其他指令使用这个?)

概括

综合以上几点我们有:

RewriteEngine On


# Redirect to https://www

RewriteCond %{HTTP_HOST} ^example\.com$

RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


# Stop here if already index.php

RewriteRule ^index\.php$ - [L]


# Only if NOT a FILE (non-existent file)

RewriteCond %{REQUEST_FILENAME} !-f

# Rewrite to index.php (in the document root)

RewriteRule . /index.php [L]

请注意,这仍然会将目录重写为,与您的评论/index.php所述相反。


首先使用 302(临时)重定向进行测试以避免潜在的缓存问题。


在测试之前您需要清除浏览器缓存。


查看完整回答
反对 回复 2023-09-22
?
慕容森

TA贡献1853条经验 获得超18个赞

经过大量的修改/研究,我发现这个有效:


RewriteEngine On

RewriteBase /

RewriteRule ^index\.php$ - [L] #if not already index.php


RewriteCond %{REQUEST_FILENAME} !-f #only if NOT a FILE (directory / non-existent file)

RewriteRule . /index.php [L] #redirect to index.php


RewriteCond %{HTTP_HOST} ^example.com$

RewriteRule ^(.*) https://www.example.com/%{REQUEST_FILENAME} [R=301,L] #redirect to https://www

</IfModule>


<IfModule mod_headers.c>

    Header set Access-Control-Allow-Origin "*"

</IfModule>


查看完整回答
反对 回复 2023-09-22
  • 2 回答
  • 0 关注
  • 58 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信