【问题标题】:How do I resolve the conflict of rules in this .htaccess file?如何解决此 .htaccess 文件中的规则冲突?
【发布时间】:2012-03-28 04:58:30
【问题描述】:

如果我注释掉另一个,文件中的每个规则都可以正常工作,但是它们两个一起不能达到任何目的,反而会使网站变得丑陋。关于如何解决这个问题的任何建议?谢谢。

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# If the request is for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
# If the request is for a valid link
RewriteCond %{REQUEST_FILENAME} !-l
# do not do anything
RewriteRule ^ - [L]

# forward /blog/foo to blog.php/foo
RewriteRule ^blog/(.+)$ blog.php/$1 [L,NC]

# forward /john to user_page/profile.php?name=john
RewriteRule ^((?!blog/).+)$ user_page/profile.php?uid=$1 [L,QSA,NC]

【问题讨论】:

    标签: php apache .htaccess mod-rewrite


    【解决方案1】:

    尝试将RewriteRule ^((?!blog/).+)$ 替换为RewriteRule ^(.+)$,无需再次检查blog 字符串

    【讨论】:

    • 我试过了,它将所有传入的url映射到user_page/profile.php
    • htaccess 工作流程是自上而下的,所以把你所有的规则放在这之前。其余的将转发到 profile.php
    【解决方案2】:

    我终于想通了。我修改了第二个重写条件,因为第二个重写规则重定向到一个不必要有效的 url,即 www.example.com/username 到看起来像这样 www.example.com/user_page/profile.php?user=username 的预期有效 url。

    我还按照 Safarov 的建议修改了最后/第二次重写规则,它奏效了!以下是完整的.htaccess 文件。

    Options +FollowSymLinks -MultiViews
    # Turn mod_rewrite on
    RewriteEngine On
    RewriteBase /
    
    # If the request is for a valid directory
    RewriteCond %{REQUEST_FILENAME} -d [OR]
    # OR If the request is for a valid file
    RewriteCond %{REQUEST_FILENAME} -f  [OR]
    # OR If the request is for a valid link
    RewriteCond %{REQUEST_FILENAME} -l
    # do not do anything
    RewriteRule ^ - [L]
    
    # forward /blog/foo to blog.php/foo
    RewriteRule ^blog/(.+)$ blog.php/$1 [L,NC]
    
    # forward /john to user_page/profile.php?name=john
    RewriteRule ^(.+)$ user_page/profile.php?uid=$1 [L,QSA]
    

    【讨论】:

    • +1 用于解决所有问题。但是,我对您的代码进行了小幅更正,并冒昧地编辑了您的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2011-07-27
    • 2021-04-13
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    相关资源
    最近更新 更多