【问题标题】:htaccess redirect conflicts with existing rewrite rulehtaccess 重定向与现有的重写规则冲突
【发布时间】:2013-07-25 16:18:36
【问题描述】:

我将所有传入我网站的 URL 请求都转换为 GET 参数,因此 fruits.com/apple 变为 fruits.com/?url=apple 并且我的路由机制负责显示正确的视图。

.htaccess

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !index.php
RewriteRule .* index.php?url=$0 [QSA,L]

这很好用。但是我现在有一些例外,我希望这些 URL 重定向到主页。 Redirect与上述规则冲突:

Redirect /pineapple /
Redirect /grapes /

这会重定向到fruits.com/?url=pineapple 而不仅仅是fruits.com

如何干净地重定向到fruits.com

可怕的解决方案

我能想到一种解决方案,除了几个例外之外,它是非常不优雅的:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !index.php
RewriteCond %{REQUEST_URI} !^/pineapple$
RewriteCond %{REQUEST_URI} !^/grapes$
RewriteRule .* index.php?url=$0 [QSA,L]

Redirect /pineapple /
Redirect /grapes /

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    用这个替换你的代码:

    通过httpd.conf启用mod_rewrite和.htaccess,然后把这段代码放到你.htaccessDOCUMENT_ROOT目录下:

    Options +FollowSymLinks -MultiViews
    # Turn mod_rewrite on
    RewriteEngine On
    
    RewriteRule ^(pineapple|grapes)/? /? [L,NC,R=301]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !index.php
    RewriteRule .+ index.php?url=$0 [QSA,L]
    

    【讨论】:

    • 成功!我不需要Options,但你的RewriteRule 成功了。它现在完全按照我想要的方式工作,非常感谢。
    • 不客气,是的,我知道这个简单的案例不需要选项,但我仍然提供了它们,因为我试图提供完整的答案。
    【解决方案2】:

    在代码方面,我们不太关心优雅,而更关心性能。

    RewriteBase /
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !index.php
    RewriteCond %{REQUEST_URI} !^/(pineapple|grapes)/?$
    RewriteRule .* index.php?url=$0 [QSA,L]
    
    RewriteRule (pineapple|grapes)/? / [R,L]
    

    如果您可以访问httpd.conf,如果您担心它的外观,可以使用rewritemap

    【讨论】:

    • 很公平。您的解决方案中的重定向有效,但在 URL 中仍然可以看到 /pineapple/grapes
    • 抱歉,忘记了硬重定向标志。
    【解决方案3】:

    切换到带有 R 标志的 RewriteRule 而不是 Redirect。如果此规则匹配,您还将使用 RewriteRule 上的 L 标志告诉 Apache 停止处理其他规则。所以你把它放在你的其他规则之上

    RewriteEngine on
    
    RewriteRule ^pineapple / [R=301,L]
    RewriteRule ^apple / [R=301,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !index.php
    RewriteRule .* index.php?url=$0 [QSA,L]
    

    【讨论】:

    • 很抱歉,这行不通。它继续到fruits.com/pineapple/
    • 打字太快了。在我应该使用^的地方使用了/^ 是为了防止你匹配 fruits.com/subdir/apple 如果你想在任何地方匹配苹果,而不仅仅是在开始时删除它。
    猜你喜欢
    • 2017-02-20
    • 2012-06-09
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多