具体来说,我希望将所有非www页面重定向到www,同时运行位于我根目录中的index.php文件。为了解决这两个问题,我使用.htaccess。
我已经将我的站点设置为在每个目录中运行PHP文件。但当我把重定向从非www加到www的那一刻,它就断了。
问题似乎是,多个重写规则相互冲突。要么一个运行,另一个没有运行,或者网站只是响应一个500错误。
我的问题是,应该将多个重写规则“合并”成一个吗?还是我只是把那些规则搞错了?(还是我搞砸了一些奇怪的语法问题?)我做这件事已经有一段时间了
任何帮助都是非常感谢的。
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
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>发布于 2020-08-11 12:51:19
--我发现这是有用的:
RewriteEngine On RewriteBase / RewriteRule ^index.php$ -L#如果还没有index.php RewriteCond %{REQUEST_FILENAME} !-f #,仅当不是文件(目录/不存在的文件) RewriteRule。/index.php L#重定向到index.php RewriteCond %{HTTP_HOST} ^example.com$ RewriteRule ^(.*) https://www.example.com/%{REQUEST_FILENAME} R=301,L#重定向到https://www
这不可能像所写的那样“工作”,因为有一些错误:
<IfModule mod_rewrite.c>指令。但是,无论如何,这个<IfModule>包装器并不是必需的,应该删除。Apache不支持
RewriteCond %{REQUEST_FILENAME} !-f #如果不是文件(目录/不存在的文件)
(更新:如果您在这里没有看到500个错误响应,那么您可能在LiteSpeed服务器上,而不是Apache?在LiteSpeed上,这个行尾注释看起来像预期的那样工作!)
www,除了请求目录(包括根目录)或实际文件(index.php除外)之外,从来不处理其他任何东西。这个重定向需要先进行,然后再进行现有的重写。不过,请看下一点.REQUEST_FILENAME (绝对文件系统路径)--这将导致格式错误的重定向。您可以使用REQUEST_URI服务器变量(完整的URL-path),但请注意,您也存在双斜杠问题。因此,它需要重写如下: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 (临时)重定向进行测试,以避免潜在的缓存问题。
在测试之前,您需要清除浏览器缓存。
发布于 2020-08-11 02:41:37
经过大量的修修补补/研究,我发现这是可行的:
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>https://stackoverflow.com/questions/63347936
复制相似问题