我有一个类似 url
localhost/index?id=2
如何使用htaccess隐藏id部分并仅显示:
localhost/index/2
为了捕获查询字符串,您需要使用 %{QUERY_STRING}
或 %{THE_REQUEST}
:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
# Redirect /index?id=2 to /index/2
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}'s/+index'?id=([^&'s]+) [NC]
RewriteRule ^ /index?%1 [R=302,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}'.php -f
RewriteRule ^(.*)$ $1.php [QSA,L]
鉴于您没有其他可能与您的需求冲突的规则,这应该可以正常工作。
确认其工作后,您可以从 302
,更改为301
,但为了避免缓存,应始终使用 302
进行测试。
使用%{THE_REQUEST}
的另一种方法是这样的:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
# Redirect /index?id=2 to /index/2
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}'s/+index'?id=([^&'s]+) [NC]
RewriteRule ^ /index/%1? [R=302,L]
# Internally forward /index/2 to /index.php?id=2
RewriteRule ^index/([0-9]+)/?$ /index.php?id=$1 [QSA,NC,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}'.php -f
RewriteRule ^(.*)$ $1.php [QSA,L]
RewriteEngine On
RewriteRule ^([A-Za-z0-9-+_%*?]+)/?$ index.php?id=$1 [L]
([A-Za-z0-9-+_%*?+) <-- 括号中的这部分用作正则表达式,表示您正在寻找从 A 到 z 和从 a 到 z 的任何字符以及从 0 到 9 和符号 - 、+,_、%,*,?右方括号后面的 + 号表示不止一个 .
简而言之,您要求哪个是([在这里]+)并且它不止一个,但是如果您删除括号后的 + 符号,它将只返回第一个字符