求助:将HTACCESS重写规则转换为Nginx规则
Apache .htaccess 重写规则转 Nginx 配置方案
你需要把 Apache .htaccess 里的这条重写规则迁移到 Nginx:
RewriteRule profile/([/.]+)/?$ profile.php?id=$1 [L]
你之前试的配置没生效:
rewrite profile.php?id=$1 ^profile/([0-9]+)/?$ break;
问题出在哪
你之前的配置有两个明显错误:
- Nginx 的
rewrite指令是先写匹配规则,再写要跳转的目标路径,你完全写反了顺序 - 原 Apache 规则允许匹配除了斜杠和点之外的任意字符(
[^/\.]+),但你改成了只匹配数字([0-9]+),范围缩得太小了
正确的配置写法
直接用下面的配置替换就行:
rewrite ^/profile/([^/.]+)/?$ /profile.php?id=$1 last;
简单解释下
^/profile/([^/.]+)/?$:匹配以/profile/开头的路径,后面可以跟任意不含斜杠和点的字符,末尾的斜杠是可选的/profile.php?id=$1:把请求转到profile.php,并用$1把刚才匹配到的内容作为id参数传过去last:和 Apache 里的[L]作用一样,意思是这条规则处理完就停,不再往下匹配其他重写规则
要是你想在location块里配置,也可以用更高效的try_files写法(更推荐):
location ~ ^/profile/([^/.]+)/?$ { try_files $uri $uri/ /profile.php?id=$1; }
内容的提问来源于stack exchange,提问作者user1864072
相关产品推荐
相关产品推荐

