【问题标题】:rewrite rule works but does not stop when matched in .htaccess重写规则有效,但在 .htaccess 中匹配时不会停止
【发布时间】:2015-05-29 21:38:13
【问题描述】:

我在 [.htaccess] 文件中添加了以下规则:

RewriteRule ^welcome/?$ index.php [NC,L] 
RewriteRule ^bye/?$ bye.php [NC,L]  
RewriteRule ^.*/?$ error.html [NC,L]

当我输入http://localhost/welcome 时,它会进入错误页面而不是索引页面。

但是当我删除 .htaccess 文件中的最后一条规则时,它会显示索引页面。匹配第一条规则时不应该停止吗?

我想阻止用户通过在 URL 栏中输入直接访问索引页面。

怎么了?

【问题讨论】:

    标签: php regex apache .htaccess mod-rewrite


    【解决方案1】:

    您需要在单独的规则中检查REDIRECT_STATUS,以验证规则是否已运行一次。

    RewriteEngine On
    
    # check if rules have run once
    RewriteCond %{ENV:REDIRECT_STATUS} !^$
    RewriteRule ^ - [L]
    
    # block direct access to index.php
    RewriteCond %{THE_REQUEST} /index\.php [NC]
    RewriteRule ^ - [F]
    
    # your default rules
    RewriteRule ^welcome/?$ index.php [NC,L] 
    RewriteRule ^bye/?$ bye.php [NC,L]  
    RewriteRule .* error.html [L]
    

    【讨论】:

    • 您通常会给出很好的答案,但在这种情况下,我认为这很困难。不是吗? :)
    • 不,如果您阅读 OP 的 2 个要求,这并不难 :)
    • 但是第二条规则没有效果。因为当我从 htaccess 中删除时,它会阻止直接访问 index.php 。表示最后一条规则适用于阻止访问所有其他页面。
    • 第二条规则仅在有人输入 URL ashttp://example.com/index.php 并得到 403 时才有用。
    猜你喜欢
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多