nginx location 块需以 ~ 或 ~* 显式启用正则匹配才能捕获路径参数,普通前缀匹配不支持;捕获组用()定义,值通过$1、$2在rewrite或proxy_pass中引用,且仅在当前location内有效。

Nginx 的 location 块支持正则表达式匹配,配合 rewrite 指令可实现动态路由重写,核心在于用括号 () 捕获路径片段,并在重写目标中通过 $1、$2 等引用。
正则 location 必须以 ~ 或 ~* 开头
使用正则需显式声明:~ 区分大小写,~* 不区分。普通前缀匹配(如 location /api/)不支持捕获。
-
location ~ ^/user/(\d+)/profile$ { ... }—— 匹配/user/123/profile,捕获123到$1 -
location ~* ^/static/(.+)\.(js|css|png)$ { ... }—— 不区分大小写,捕获文件名和后缀 - 注意:正则 location 的优先级低于精确匹配(
=)和最长前缀匹配,但高于普通前缀匹配;多个正则按配置顺序从上到下匹配,命中即停
rewrite 中引用捕获组并控制跳转行为
在匹配成功的 location 内,用 rewrite 重写 URI,捕获变量直接写作 、 等。末尾标志决定后续流程:
当代理已经知道网站路由或内容URL,并且在启动前需要有效的sitemap XML、sitemap索引或robots.txt引用时,请使用sitemap。这是一个发布构件技能,而不是爬虫或SEO平台。
-
last:重写后重新匹配 location(常用,适合内部跳转) -
break:重写后停止处理,不重新匹配(适合终止当前 location 流程) -
redirect:302 临时重定向(返回 HTTP 302) -
permanent:301 永久重定向
例如:
location ~ ^/v(\d+)/products/(\d+)$ {rewrite ^/v\d+/products/(\d+)$ /api/products?id=$2&version=$1 last;
}
捕获内容可用于 proxy_pass 或其他指令
捕获变量不仅用于 rewrite,也可传给 proxy_pass、fastcgi_param 等。注意:proxy_pass 后带 URI 时,会替换掉匹配的 location 路径部分;若想保留捕获逻辑,建议用 rewrite 统一处理后再 proxy_pass。
- 安全做法:先 rewrite 成标准格式,再由通用 location 处理 proxy_pass
- 避免陷阱:不要在
proxy_pass http://backend/$1中直接拼接捕获变量——Nginx 不支持在 proxy_pass 中解析变量(除非用http://backend+ rewrite 配合) - 正确示例:
location ~ ^/app/([a-z]+)/(\d+)$ {
rewrite ^/app/([a-z]+)/(\d+)$ /internal/app/$1?id=$2 break;
proxy_pass http://backend;
}
调试技巧与常见坑点
正则重写易出错,建议开启日志验证实际匹配与重写结果:
- 在 http 或 server 块中加:
log_format debug '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$request_uri" "$uri" "$document_uri" "$args"'; - 用
error_log /path/error.log notice;查看 warning 级别提示(如“regex matching”) - 常见问题:
• 忘记转义特殊字符(如.应写为\.)
• 括号嵌套未闭合导致语法错误
• 使用$1但正则未定义捕获组(Nginx 不报错,值为空)
• rewrite 在 location 外使用 —— 必须在 server 或 location 块内










