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

具体来说,我想将所有非 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>


慕妹3242003
浏览 62回答 2
2回答

青春有我

我发现这个有效:RewriteEngine OnRewriteBase /RewriteRule ^index\.php$ - [L] #if not already index.phpRewriteCond %{REQUEST_FILENAME} !-f #only if NOT a FILE (directory / non-existent file)RewriteRule . /index.php [L] #redirect to index.phpRewriteCond %{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 错误:&nbsp;RewriteCond&nbsp;%{REQUEST_FILENAME}&nbsp;!-f&nbsp;#only&nbsp;if&nbsp;NOT&nbsp;a&nbsp;FILE&nbsp;(directory&nbsp;/&nbsp;non-existent&nbsp;file)(更新:如果您在此处没有看到 500 错误响应,则您可能使用的是 LiteSpeed 服务器;而不是 Apache?在 LiteSpeed 上,此行尾注释似乎按预期工作!)www除了对目录(包括根目录)或真实文件(除了index.php)的请求之外,重定向到的外部重定向(最后)永远不会被处理。在现有重写之前,需要先进行此重定向。然而,请看下一点......您在目标 URL 中错误地使用了REQUEST_FILENAME(绝对文件系统路径) - 这将导致格式错误的重定向。您可以使用REQUEST_URI服务器变量(完整的 URL 路径),但请注意,您还存在双斜杠问题。因此,它需要像下面这样重写:&nbsp;RewriteRule&nbsp;^&nbsp;https://www.example.com%{REQUEST_URI}&nbsp;[R=301,L]小要点:RewriteBase这里没有使用它,可以安全地删除。(除非你有其他指令使用这个?)概括综合以上几点我们有:RewriteEngine On# Redirect to https://wwwRewriteCond %{HTTP_HOST} ^example\.com$RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]# Stop here if already index.phpRewriteRule ^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(临时)重定向进行测试以避免潜在的缓存问题。在测试之前您需要清除浏览器缓存。

慕容森

经过大量的修改/研究,我发现这个有效:RewriteEngine OnRewriteBase /RewriteRule ^index\.php$ - [L] #if not already index.phpRewriteCond %{REQUEST_FILENAME} !-f #only if NOT a FILE (directory / non-existent file)RewriteRule . /index.php [L] #redirect to index.phpRewriteCond %{HTTP_HOST} ^example.com$RewriteRule ^(.*) https://www.example.com/%{REQUEST_FILENAME} [R=301,L] #redirect to https://www</IfModule><IfModule mod_headers.c>&nbsp; &nbsp; Header set Access-Control-Allow-Origin "*"</IfModule>
打开App,查看更多内容
随时随地看视频慕课网APP