dav*_*aro 9 mod-rewrite rewrite apache-2.2
我使用以下代码将所有 www 请求定向到非 www URL:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.org$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
Run Code Online (Sandbox Code Playgroud)
这在我网站根目录的 .htaccess 文件中非常有效。
例如,
www.example.com -> example.com/www.example.com/
-> example.com/www.example.com/other_page
-> example.com/other_page
但是,如果我将相同的代码移动到我的 VirtualHost 配置中,重写的 URL 将包含一个双斜杠。
www.example.com -> example.com//
www.example.com/ -> example.com//
www.example.com/other_page -> example.com//other_page
我通过从重写规则中删除斜杠来修复它:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.org$ [NC]
RewriteRule ^(.*)$ http://example.com$1 [R=301,L]
Run Code Online (Sandbox Code Playgroud)
但我无法理解这样做的原因。有谁知道为什么?
Neo*_*yte 10
据我了解,在 .htaccess 文件中,mod_rewrite 在您的规则中处理的字符串与 .htaccess 文件所在的目录相关,因此它的开头不会有 /。
在 VirtualHost 条目中,它处理的字符串对于服务器的根是绝对的,因此包括 /。
它在 mod_rewrite 的工作方式上产生了细微的差异。
这是一个有类似问题的人,以及解决方案:
http://forum.modrewrite.com/viewtopic.php?p=56322&sid=77f72967f59200b5b5de174440234c3a
这应该适用于两种情况,假设我记得我的转义正确:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.org$ [NC]
RewriteRule ^\/?(.*?)$ http://example.com/$1 [R=301,L]
Run Code Online (Sandbox Code Playgroud)