【问题标题】:Use mod_rewrite to redirect from example.com/dir to www.example.com/dir使用 mod_rewrite 从 example.com/dir 重定向到 www.example.com/dir
【发布时间】:2011-05-30 20:20:34
【问题描述】:

假设 / 是我的域 example.com 的文档根。

/.htaccess

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

/dir/.htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /dir/index.php [L]
</IfModule>

我知道如何将example.com/dir 重定向到www.example.com/dir,因为/.htaccess 可以完成这项工作。

但是,这里的诀窍是,如果您明白我的意思,我必须保留 /dir/.htaccess 来提供虚拟目录(例如 /dir/state/AK/35827/,它们不是实际目录)。

问题是,如果我保留/dir/.htaccess,请求:

http://example.com/dir/state/AK/35827/

不重定向到:

http://www.example.com/dir/state/AK/35827/

原样:

http://example.com/

重定向到:

http://www.example.com/

不确定我是否说清楚了。

基本上,如何使http://example.com/dir/state/AK/35827/ 正确重定向到http://www.example.com/dir/state/AK/35827/ 并且我可以提供虚拟网址?

【问题讨论】:

    标签: apache .htaccess mod-rewrite redirect


    【解决方案1】:

    如果您确实可以访问您的 apache VirtualHosts 配置,那么您需要:

    <VirtualHost *:80>
        ServerName example.com
        Redirect permanent / http://www.example.com/
    </VirtualHost>
    

    这将成功地将http://example.com/ 重定向到http://www.example.com/http://example.com/dir/state/AK/35827/http://www.example.com/dir/state/AK/35827/

    【讨论】:

    • 谢谢。我无权访问 VirtualHosts 配置。有没有其他方法可以做到这一点?
    【解决方案2】:

    这里的“问题”是 mod_rewrite 默认不“继承”父配置(.htaccess)。子目录中的 mod_rewrite 指令完全覆盖了父目录中的 mod_rewrite 指令(与其他模块不同)。

    您需要:

    • 将规范的 www 重定向从父 .htaccess 文件复制到 /dir/.htaccess。但是代码重复是不可取的。

    • 或者:在子 .htaccess 文件中启用 mod_rewrite 继承:

      RewriteOptions inherit
      

      这有效地“复制”了来自父 .htaccess 文件的 mod_rewrite 指令。但是,如果您有其他指令,这可能无法按预期工作。请注意,这会“复制”指令,而不更改目录前缀。

    • 或者:在父 .htaccess 文件中执行所有操作。拥有一个 .htaccess 文件可能是首选的解决方案。例如:

      RewriteEngine on
      
      # Canonical redirect
      RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
      RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
      
      # Virtual directories...
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^dir/ dir/index.php [L]
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多