如何用.htaccess将带参数的PHP动态URL重写为静态路径?
.htaccess重写规则实现动态URL美化
原始动态URL示例:
http://localhost/index.php?city=Delhi http://localhost/index.php?city=Delhi&page=AboutUs http://localhost/index.php?city=Delhi&page=Blog&Read=AnyBlog http://localhost/index.php?city=Delhi&page=Treatment&type=AnyTreatment
目标静态化URL示例:
http://localhost/Delhi http://localhost/Delhi/AboutUs http://localhost/Delhi/Blog/AnyBlog http://localhost/Delhi/Treatment/AnyTreatment
对应的.htaccess重写代码:
将以下代码保存为.htaccess文件,放在网站根目录(与index.php同级):
RewriteEngine On # 匹配单一城市参数的URL RewriteRule ^([A-Za-z0-9-]+)/?$ index.php?city=$1 [L,QSA] # 匹配城市+基础页面的URL RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ index.php?city=$1&page=$2 [L,QSA] # 匹配Blog页面带Read参数的URL RewriteRule ^([A-Za-z0-9-]+)/Blog/([A-Za-z0-9-]+)/?$ index.php?city=$1&page=Blog&Read=$2 [L,QSA] # 匹配Treatment页面带type参数的URL RewriteRule ^([A-Za-z0-9-]+)/Treatment/([A-Za-z0-9-]+)/?$ index.php?city=$1&page=Treatment&type=$2 [L,QSA]
规则说明:
RewriteEngine On:开启URL重写功能(需确保服务器已启用mod_rewrite模块)- 每条
RewriteRule的正则部分匹配目标URL结构,将对应片段映射到原动态URL的参数中 /?$`:允许URL结尾带或不带斜杠,提升兼容性[L,QSA]:L表示匹配当前规则后停止后续规则处理;QSA保留额外查询参数(若URL含其他参数时生效)- 正则
[A-Za-z0-9-]+限制参数值仅包含字母、数字和连字符,若需支持下划线等字符,可调整为[A-Za-z0-9-_]+
内容的提问来源于stack exchange,提问作者dvijai
相关产品推荐
相关产品推荐

