【问题标题】:301 redirect URLs that are also being rewritten301 重定向 URL 也被重写
【发布时间】:2015-06-25 23:29:06
【问题描述】:

我正在使用 Slim 构建一个网站,它建议使用以下 .htaccess 代码来创建漂亮的 URL:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

这意味着像 http://example.com/account/login 这样的 URL 将为 http://example.com/index.php/account/login别名,然后由我的前端控制器处理。到目前为止一切顺利。

但是,如果有人明确导航到

http://example.com/index.php/account/login,

我希望它首先重定向到:

http://example.com/account/login,

然后

的别名

http://example.com/index.php/account/login

这样,用户将在他们的导航栏中看到http://example.com/account/login

如何在.htaccess 中同时处理这两个规则,最重要的是,无需在.htaccess 中对主机和域 (http://example.com) 进行硬编码?

这也应该在子目录中工作,例如:

http://example.com/site1/index.php/account/login -> http://example.com/site1/account/login

.htaccess 文件位于相对于文档根目录的site1 目录中,并且无需将site1 显式放入.htaccess

【问题讨论】:

    标签: php .htaccess mod-rewrite redirect slim


    【解决方案1】:

    在这条规则之前你需要一个新的重定向规则:

    RewriteEngine On
    
    RewriteCond $0#%{REQUEST_URI} ^([^#]*)#(.*)\1$
    RewriteRule ^.*$ - [E=BASE:%2]
    
    RewriteCond %{THE_REQUEST} /index\.php [NC]
    RewriteRule ^index\.php(?:/(.*))?$ %{ENV:BASE}$1 [L,R=302,NC,NE]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]
    

    【讨论】:

    • 嗯,我在另一个问题中看到了你的答案,但它似乎对我不起作用。如果我在RewriteRule 模式的开头有^,那不是要从一开始就尝试匹配URL吗?
    • 这个答案实际上是正确的 - 不知道你在一开始就匹配 URL 是什么意思......它只是没有重定向吗?
    • 这适用于http://localhost/index.php/blah,但不适用于http://localhost/site1/index.php/blah(假设我的.htaccess 文件位于相对于我的文档根目录的/site1 目录中)。
    • 如果您的 .htaccess 在 site1 中,那么您需要一个 RewriteBase(参见更新后的规则)。
    • 难道没有办法对基础进行正则表达式匹配吗?否则,它将要求我的软件的每个用户单独配置他们的.htaccess。我不想增加那种额外的复杂性。
    【解决方案2】:

    试试这个:

    RewriteRule ^index\.php/(.*)$ /$1 [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
    

    【讨论】:

    • 你会认为它会那么简单,但唉......不:(
    猜你喜欢
    • 2013-12-21
    • 2015-03-04
    • 2016-09-28
    • 2023-03-25
    • 2013-01-27
    • 2011-09-01
    • 2016-05-11
    • 1970-01-01
    • 2011-01-18
    相关资源
    最近更新 更多