如何解决此.htaccess文件中的规则冲突?

时间:2012-03-27 18:32:39

标签: php apache .htaccess mod-rewrite

如果我将另一个规则注释掉,那么文件中的每个规则都能正常运行,但是它们中的两个规则并没有实现任何目的,而是使网站变得丑陋。有关如何解决此问题的任何建议?感谢。

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]

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

我终于弄明白了。我修改了第二个重写条件,因为第二个重写规则重定向到一个不必要有效的网址,即www.example.com/username到预期的有效网址www.example.com/user_page/profile.php?user=username

我还修改了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]