【问题标题】:How to make mod_rewrite redirect properly in a subdirectory without specifying the path?如何在不指定路径的情况下使 mod_rewrite 在子目录中正确重定向?
【发布时间】:2016-09-10 02:21:57
【问题描述】:

这是我的问题:

假设我有一个网站www.example.com。我有一个应用程序subdir 位于该域的文档根目录的子目录中:

/home/example/public_html/subdir/

subdir 包含此.htaccess

# Redirect trailing slash if not a directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /subdir/$1 [L,R=301]

它有效。如果我转到http://www.example.com/subdir/not_a_directory/(显然假设not_a_directory 不是目录),我会被重定向到http://www.example.com/subdir/not_a_directory,这就是我想要的。

但我不想在重写规则或.htaccess 中的任何地方指定subdir。我希望能够在不破坏任何东西的情况下更改应用程序的路径。我尝试了以下...

# Redirect trailing slash if not a directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ $1 [L,R=301]

但我被重定向到:http://www.example.com/home/example/public_html/subdir/not_a_directory

我有点理解为什么会发生这种情况(重写规则的相对路径返回文件系统路径,而绝对或根绝对路径返回 URL),但我不知道如何实现我正在寻找的为。

有没有办法让RewriteRule 中的捕获组包含路径的subdir 部分?我也尝试设置RewriteBase /,但它似乎并没有改变任何东西。

重写规则让我很困惑,所以任何帮助都将不胜感激。谢谢!

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-rewriting


    【解决方案1】:

    您可以使用此规则,而无需在 .htaccess 中的任何位置指定 subdir

    RewriteEngine On
    
    # Remove trailing slash if not a directory
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} ^(/.+)/$
    RewriteRule /$ %1 [L,R=301,NE]
    

    RewriteCond %{REQUEST_URI} 捕获路径允许我们捕获完整的 URI 路径。

    【讨论】:

    • 好的,谢谢!我注意到REQUEST_URI 包含subdir,但我没有意识到我可以在 RewriteCond 中使用捕获组(或者更确切地说,忘记了我可以)。还有两个问题: 1. 我想我可以用RewriteRule ^ 替换RewriteRule /$,因为第二个RewriteCond 已经只会重写以斜杠结尾的URL,对吗? 2. 为什么是 NE(noescape)标志?
    • 是的 RewriteRule ^ 在这里非常好,NE 是为了避免 URL 中的一些特殊字符被编码。
    • 有没有我们不想要NE的情况?
    • 我没有遇到任何使用NE造成伤害的案例。
    【解决方案2】:

    试试这个位置进行rewritebase

    RewriteBase subdir/
    

    【讨论】:

    • OP 写道:I don't want to have to specify subdir in the rewrite rule or anywhere in the .htaccess
    猜你喜欢
    • 2019-09-02
    • 2015-04-19
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 2019-03-28
    相关资源
    最近更新 更多