Nginx rewrite规则本质是URL重写,通过rewrite指令配合正则表达式和flag(如last、break、redirect、permanent)实现路径修改或跳转,须置于server/location块中,慎用if块。
Nginx 的 rewrite 规则本质是 URL 重写,用于修改请求路径、跳转或内部重定向,核心靠 rewrite 指令配合正则表达式和标志位实现。
rewrite 必须写在 server、location 或 if 块中(不推荐在 if 中滥用),格式为:
rewrite <正则表达式> <替换目标> [<flag>];
~* 表示不区分大小写匹配last(内部重定向,结束当前 location 匹配后重新搜索;break(停止 rewrite 处理,不再执行后续 rewrite;redirect(302 临时跳转);permanent(301 永久跳转)实际中多数需求可归为几类:
rewrite ^/(.*).php$ /$1 permanent;注意需配合 fastcgi_pass 正确处理,否则可能 404if ($scheme = http) { rewrite ^ https://$host$request_uri? permanent; }更推荐用 return(性能更好):return 301 https://$host$request_uri;
location / { try_files $uri $uri/ /index.html; }或显式 rewrite:rewrite ^(.*)$ /index.html last;(需确保 index.html 存在)rewrite ^/old-path/(.*)$ /new-path/$1 break;使用 break 避免循环重写,且不触发 location 重匹配rewrite 容易因顺序、作用域或 flag 误用导致意外行为:
last 或 redirect 等 flag,后续 rewrite 不再执行map 或 return 替代[0-9]
error_log /path/to/log notice; 可查看 rewrite 日志(需编译时开启 --with-debug)很多 rewrite 场景其实有更简洁、安全的替代方式:
return:性能高、语义清晰,例如 return 301 https://$host$request_uri;
try_files:比 rewrite 更高效,如 SPA 路由、多级 fallbackmap 预定义变量:适合基于 host、user-agent 等条件做分流,避免嵌套 ifrewrite 功能强大但需谨慎使用,理解其执行时机和 flag 差异是关键。简单跳转用 return,路径改写用 rewrite + break/last,复杂逻辑尽量下沉或换方案。