【问题标题】:Using mod_rewrite in .htaccess in both website root and a subdirectory在网站根目录和子目录中的 .htaccess 中使用 mod_rewrite
【发布时间】:2008-12-03 22:25:58
【问题描述】:

我的困境:

在我网站根目录的 .htaccess 中:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

在 .htaccess 的子目录 /foo 中

RewriteEngine On
RewriteRule ^page1\.html$ /foo/page2.html [R=301]

首先,我试图确保所有请求都包含开头的 www。 在第二个中,我将对 foo 子目录中 page1.html 的请求重定向到 page2.html,也在该子目录中。

在我的浏览器中,尝试访问:

http://www.example.com/foo/page2.html

http://www.example.com/foo/page1.html http://www.example.com/foo/page2.html,很好

http://example.com/foo/page1.html http://www.example.com/foo/page2.html,很好

http://example.com/foo/page2.html

==> 应该重定向到:http://**www.**example.com/foo/page2.html

通过实验,网站根目录中的.htaccess文件中的重定向规则似乎只对对该子目录中的页面的请求生效如果该子目录不包含.htaccess文件,或者它确实并指定了对该特定请求生效的重写规则。

谁能看到我做错了什么?我怎样才能获得粘贴 www.rewrite 的重写规则。如果它缺少为http://example.com/foo/page2.html 开火?


谢谢你,成功了!

为了记录,我不得不将站点根目录中文件中的重写规则更改为:

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

这很好。谢谢!

【问题讨论】:

  • 其实你可以把第二条规则写成'RewriteRule ^page1\.html$ page2.html [R=301]';请参阅 RewriteBase 的文档

标签: apache .htaccess mod-rewrite


【解决方案1】:

您在foo/.htaccess 中缺少以下指令:

RewriteOptions inherit

参见。 the documentation

【讨论】:

    【解决方案2】:

    我不确定为什么/.htaccess 中的规则不适用于/foo/.htaccess。通常,.htaccess 文件将继承目录结构的规则,这可能会导致各种奇怪的事情。不过,对于您的具体解决方案,您可以将所有相关规则放在您的父 .htaccess 文件中,如下所示:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
    RewriteRule ^foo/page1\.html$ /foo/page2.html [R=301]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多