如何为.htaccess编写多个条件和规则?

时间:2013-03-01 00:30:54

标签: apache .htaccess mod-rewrite

我在我的网站的.htaccess文件中有以下内容

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteRule ^(.*)$ profile.php?membername=$1 [L]
    RewriteRule ^poem/(.*)/?$ poem.php?id=$1 [L,NC]
</IfModule>


# Works
RewriteRule ^(.*)$ profile.php?membername=$1 [L]
# Does not work
RewriteRule ^poem/(.*)/?$ poem.php?id=$1 [L,NC]

如果改变这一点,那么结果就会逆转。

# No longer works:
RewriteRule ^(.*)$ profile.php?membername=$1 [L]
# Now works:
RewriteRule ^poem/(.*)/?$ poem.php?id=$1 [L,NC]


<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{SCRIPT_FILENAME} -f
    RewriteCond %{SCRIPT_FILENAME} -d
    RewriteRule ^(.*)$ profile.php?membername=$1 [L]
    RewriteRule ^poem/(.*)/?$ poem.php?id=$1 [L,NC]
</IfModule>

发生了什么事?我不知道。

1 个答案:

答案 0 :(得分:2)

看起来你需要做的就是在REQUEST_FILENAME上保留负面测试,并颠倒规则的顺序。否则,通用^(.*)总是先匹配,并取代^poem/

<IfModule mod_rewrite.c>
    RewriteEngine On
    # Negative conditions here...
    # Using REQUEST_FILENAME instead of SCRIPT_FILENAME
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # Match the more specific rule first...
    RewriteRule ^poem/(.*)/?$ poem.php?id=$1 [L,NC]

    # Match the generic rule last.
    RewriteRule ^(.*)$ profile.php?membername=$1 [L]
</IfModule>