Nginx rewrite规则本质是用正则匹配请求URI并改写路径,必须置于server或location块内,按顺序执行,依赖标志位(last/break/redirect/permanent)控制流程与匹配行为。
Nginx 的 rewrite 规则本质是用正则匹配请求 URI,再按规则跳转或改写路径。它不复杂,但容易因匹配顺序、标志位或上下文位置出错。
rewrite 必须放在 server 或 location 块里,不能直接写在 http 块顶层。不同位置行为不同:
server 块中:对所有进入该虚拟主机的请求,在 location 匹配前统一处理location 块中:只对匹配到该 location 的请求生效,且重写后会重新进行 location 匹配(除非加 last)if 块里滥用 rewrite(Nginx 最新不推荐),尤其不要在 if 中做非变量判断(如 if ($request_uri ~* ...))格式为:rewrite 正则 替换串 标志;
$request_uri(不含域名和参数,含开头斜杠),建议用 ^/old/(.*)$ 这类锚定写法,避免误匹配$1, $2),也可拼接新路径,如 /new/$1
last:重写后停止当前 location 处理,用新 URI 重新匹配 location(常用)break:重写后不再匹配其他 rewrite,也不重新 location 查找(适合内部路径改写)redirect:返回 302 临时跳转(加 https:// 或完整 URL 才生效)permanent:返回 301 永久跳转例如把 /article/123 改成 /post?id=123:
rewrite ^/article/(d+)$ /post?id=$1? last;
注意结尾的 ? 可清空原始 query string,避免变成 /post?id=123?old=param
rewrite ^(.*[^/])/$ $1 permanent;
rewrite ^(.*)$ https://$host$1 permanent;(需配合 if ($scheme != "https") 使用,但更推荐用 return 301)rewrite ^/(.*).php$ /$1 last;,再配合 try_files $uri.php $uri =404;
rewrite 不生效?先检查这几项:
^ 和 $ 锚定整个 URI)error_log /path/to/log warn;,rewrite 失败或循环会报 rewrite or internal redirection cycle
break 截断/static/xxx.png,就得有对应 location /static/)