您的重写规则基于正则表达式,因此需要尽可能具体,以便服务器可以准确确定要使用的 url - 例如,您如何判断http://example.com/something是页面还是配置文件? 在您的 URL 上使用诸如“user”、“profile”等前缀意味着http://example.com/profile/something可以作为用户名重定向,而其他所有内容的默认重定向。要做到这一点,您需要首先进行更具体的模式匹配(用户)并使用该[L]
指令指示不应处理以下规则。我通常对 URL 使用负字符类来匹配除正斜杠之外的任何内容 - [^/]*
。
# Enable mod_rewrite
RewriteEngine On
# Set the base directory
RewriteBase /
# Don't process if this is an actual file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Does this url start with /profile and then followed with additional characters?
RewriteRule ^profile/([^/]*)$ profile.php?username=$1 [NC,L]
# Assume everything else is a page
RewriteRule ^(.*)$ index.php?page=$1 [NC,L]
在http://htaccess.madewithlove.be/进行测试(请注意,%{REQUEST_FILENAME}
不%{REQUEST_FILENAME}
支持测试)。
轮廓
input url
http://www.example.com/profile/something
output url
http://www.example.com/profile.php
debugging info
1 RewriteRule ^profile/([^/]*)$ profile.php?username=$1 [NC,QSA,L]
This rule was met, the new url is http://www.example.com/profile.php
The tests are stopped because the L in your RewriteRule options
2 RewriteRule ^(.*)$ index.php?page=$1 [NC,L]
页
input url
http://www.example.com/something
output url
http://www.example.com/index.php
debugging info
1 RewriteRule ^profile/([^/]*)$ profile.php?username=$1 [NC,L]
2 RewriteRule ^(.*)$ index.php?page=$1 [NC,L]
This rule was met, the new url is http://www.example.com/index.php
The tests are stopped because the L in your RewriteRule options