这是《Nginx 从入门到精通》系列的第 6 篇(全系列 15 篇 + 4 个实战项目)。目标:把「伪静态 / 跳转 / 多域名」做成可维护的配置------能背出
server_name的五级匹配顺序,能用map替掉该替的if,能把一条.htaccess规则翻译成语义正确的 nginx 写法,并当场造出一个rewrite死循环 500。前置 :第 5 篇(反向代理与负载均衡入门)、第 4 篇(静态站点与 location 匹配)、第 3 篇(配置语法与上下文);实验复用
lab/00-env(按需)。 本文所有数字与输出均为 nginx 1.30.6(stable)实测,文末附自测 5 题与延伸阅读。
1. 先跑起来(5 分钟实验)
环境先起(已起可跳过):cd nginx/lab/00-env && docker compose up -d;然后在 nginx/conf.d/default.conf 的 server { } 里、location / 之前插 4 条:
nginx
location = /hello { return 200 "hello\n"; }
location = /go { return 301 /hello; }
location ~ ^/post/(\d+)$ { rewrite ^/post/(\d+)$ /index.php?p=$1 last; }
location ~ ^/index\.php$ { proxy_pass http://app_pool; proxy_set_header Host $host; }
bash
docker compose exec -T gateway nginx -t -c /etc/nginx/lab/nginx.conf # 必须带 -c
docker compose exec -T gateway nginx -s reload
curl -s localhost:8080/hello
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' localhost:8080/go
curl -s localhost:8080/post/123
| 命令 | 预期输出(实测) | 谁在干活 |
|---|---|---|
curl -s localhost:8080/hello |
hello |
return 200,内容阶段完全不参与 |
curl -s ... localhost:8080/go |
301 http://localhost/hello |
return 301 带相对 URI,由 $scheme+$host 补全 |
curl -s localhost:8080/post/123 |
app=app1 换行 path=/index.php?p=123 |
rewrite ... last 改 URI → 重新匹配到 .php 的 location → 反代 |
curl -s localhost:8080/api/json |
与实验前一致(轮询 app1/2/3) | 本篇不碰 /api/ |
app=appN 的名字随轮询变化(第 5 篇),path= 才是本篇要盯的字段 ------它就是上游真正收到的 URI。改完没生效时先看 -t 的输出:漏掉 -c /etc/nginx/lab/nginx.conf 校验的是镜像自带默认配置,等于没校验,reload 自然也加载不到你改的文件;反过来,reload 不需要 -c------master 记着自己启动时的配置路径。
2. 核心概念
2.1 一条请求的四个阶段:谁先说话
| 阶段 | 谁在里面干活 | 本篇关注点 |
|---|---|---|
| 1 选 server + server 级 rewrite | server_name 匹配;server 块里的 rewrite/return/set/if |
server 级 rewrite 先于 location 匹配 |
| 2 location 匹配 | = → ^~ → 前缀 → 正则(第 4 篇) |
last 会回到这一步 |
| 3 location 级 rewrite | 同样四类指令 | break 改完就停在当前 location |
| 4 内容阶段 | proxy_pass / try_files / 静态文件 |
return 不给它机会 |
关键一句:rewrite/return/set/if/break 全在同一个 rewrite 阶段按书写顺序执行 (官方模块页原文 are executed sequentially),所以「return 一定赢过 rewrite」只在 return 写在前面时成立。常见说法「return 优先级高于 rewrite」应理解成 return 高于内容阶段的 proxy_pass/try_files ,别当成可以无视顺序------实测 location = /a { return 200 "A"; rewrite ^ /zzz last; } 返回 A,把两行对调后返回的是 /zzz 的响应。
last 与 break 的唯一区别就是「改完 URI 之后谁接手」:同样把 /xxx/json 改写成 /api/json,last 会重新匹配到 /api/ 并反代成功(200,上游收到 /json);break 则停在原 location,那里没有 proxy_pass 也没有 try_files,只能按 root 去找静态文件 /usr/share/nginx/html/api/json,于是 404。完整对照见实验 2。
2.2 四个 flag 与 return
| flag | 停止什么 | 是否重新匹配 location | 客户端看到 |
|---|---|---|---|
last |
本轮 rewrite 指令集 | 是 | 改写后的 URI 由新 location 正常响应 |
break |
本轮 rewrite 指令集 | 否 | 改写后的 URI 在当前 location 走内容阶段 |
redirect |
立刻结束 | 否 | 302 |
permanent |
立刻结束 | 否 | 301 |
| 不写 flag | 只停这一条,继续下一条 | 本轮结束后照常匹配 | 行为不变 |
replacement 以 http:///https:///$scheme 开头 |
立刻结束 | 否 | 302(不用写 redirect) |
return 的形态(官方模块页口径):
| 写法 | 结果 | 典型用途 |
|---|---|---|
return 200 "text"; |
200 + 响应体,可含变量 | 探活、维护页 |
return 301 URL; / return 302 URL; |
301 / 302 | 域名或路径迁移 |
return URL; |
单参数简写=302(URL 须以 http://、https://、$scheme 开头) |
临时跳走 |
return 403; / return 404; |
空响应体 | 用 return 替代 if 做拦截 |
return 444; |
不发响应头,直接断连(curl 退出码 52) |
丢弃扫描流量 |
版本下限:return 带 text/URL 从 0.8.42 起;307/308 分别从 1.1.16 / 1.13.0 起才被当作跳转。rewrite 循环上限 10 次 ,超出返回 500,日志里是 rewrite or internal redirection cycle while processing ...。替换串里写了新的参数(/index.php?p=$1)时,原请求的 $args 会被自动追加在后面;想让原参数彻底消失,就在替换串末尾再加一个 ?(官方示例 /show?user=$1?)------这一点和 .htaccess 的 [QSA] 语义相反,迁移时最容易看漏。
2.3 「if is evil」的真实含义
if 在配置解析阶段被实例化成一份独立(嵌套)配置,只有 rewrite 模块的指令在它里面有确定语义:
| 用法 | 结果 | 证据 |
|---|---|---|
if 里写 return / rewrite |
可靠,推荐 | 实验 3 的灰度写法就靠它 |
if 里写 proxy_pass |
语法能过,但 proxy_pass 的 URI 规则失效:URI 原样透传(含 query) |
/g4/json?new=1 上游收到 /g4/json?new=1,而 /g4/json 收到 /json |
if 里写 proxy_set_header |
nginx -t 直接失败:"proxy_set_header" directive is not allowed here |
实测 |
if 里写 add_header |
分支命中时外层 location 的 add_header 丢失 |
实测:/h?v=1 只回 X-If,没有 X-Outer |
替代顺序:能用 map/geo 解决就别写 if;能用 try_files 判断文件就别用 if (-f);能用 error_page/多 location 分流就别在 if 里写 proxy_pass。
2.4 server_name 匹配顺序
| 优先级 | 类型 | 例子 | 实测请求头 → 命中 |
|---|---|---|---|
| 1 | 精确名 | www.a.com |
Host: www.a.com → 精确块 |
| 2 | 前导通配(最长) | *.a.com |
Host: api.a.com → 通配块 |
| 3 | 后导通配(最长) | www.a.* |
Host: www.a.org → 通配块 |
| 4 | 正则(~/~*,按文件顺序取第一个命中) |
~^www\. |
Host: www.zzz → 正则块 |
| 5 | 默认 server | listen 80 default_server;都没标就是该端口第一个 |
Host: nope.example → 默认块 |
通配只允许出现在名字的开头或结尾(*.a.com、www.a.*);把 * 放到中间(a.*.b)不是合法通配位置------只要该端口上还有别的 server,nginx -t 就直接 emerg invalid server name or wildcard "a.*.b"(实测),而单 server 的端口上它反而会被静默接受成一个永远匹配不上的字面名,这类错误常在「加第二个站点」时才炸出来。同一个 server 可以写多个名字,用空格分隔,注意 $server_name 只认第一个。三条硬事实:
server_name _;里的_不是通配符,它只是个永远匹配不上的非法名,只有在该 server 同时是默认 server 时才接住流量;- 正则写
~\.dev\.local会命中evil.dev.local.attacker.com(实测返回了 dev 块的内容),必须写成~^[a-z0-9-]+\.dev\.local$; - 正则
server_name可用命名捕获~^(?<devhost>[a-z0-9-]+)\.dev\.local$,后面的return/log_format里能直接用$devhost。
2.5 $host / $server_name / $http_host
| 变量 | 来源 | 实测(Host: www.lab.local,server_name lab.local www.lab.local;) |
|---|---|---|
$host |
请求行或 Host 头,小写、去端口;缺失时退到匹配到的 server_name |
www.lab.local |
$server_name |
配置里 server_name 的第一个名字 |
lab.local ← 拼跳转别用它 |
$http_host |
原始 Host 头,保留端口 |
www.lab.local(宿主访问时是 localhost:8080) |
所以 return 301 https://$server_name$request_uri; 会把 www.lab.local 的用户跳到 lab.local;而 $host 又完全来自请求头,直接拼就是开放重定向(Host: evil.com → 301 到 evil.com,实测)。正解见第 4 节的 /jump:先 map $host $host_ok 查白名单,不在表里就 return 444。
2.6 map / geo:替代 if 的两把工具
| 工具 | 输入 | 适合 | 注意 |
|---|---|---|---|
map |
任意变量($http_*、$uri、$arg_*) |
UA 分流、旧链接映射、灰度开关、跳转白名单 | 只能放 http 上下文 ,放 server 里 -t 报 "map" directive is not allowed here(实测) |
geo |
仅 $remote_addr |
IP 段判断、内网识别 | 结果值不能用正则;要判断代理后的真实 IP 得配合第 5 篇的 real_ip |
if |
条件表达式 | 只限 return/rewrite |
其余用法见 2.3 |
map 的取值规则:精确匹配优先于正则,正则按书写顺序取第一个,default 兜底(不写时为空串);结果值默认在每个请求内只求值一次 ,依赖会变化的变量(如 $upstream_addr)时才需要 volatile(≥1.11.7 ,官方模块页标注)。map/geo 的结果本身就是一个普通变量,既能出现在 return 的文本里,也能塞进 proxy_set_header(如 proxy_set_header X-Pool $is_canary;)或 proxy_pass 的路径里------这就是「用查表替代 if」能覆盖绝大多数分流需求的原因。要写 *.lab.local 这类通配主键,得先加 hostnames;(≥1.11.3,以官方文档为准;官方模块页未标版本)。
2.7 伪静态三例与内部跳转
| 场景 | 目标 | 写法 |
|---|---|---|
| WordPress 式 | /post/123 → /index.php?p=123 |
location ~ ^/post/(\d+)$ { rewrite ^/post/(\d+)$ /index.php?p=$1 last; } |
| ThinkPHP A(推荐) | 文件存在就发文件,否则打进入口 | location / { try_files $uri $uri/ /index.php?s=$uri; } |
| ThinkPHP B(rewrite 版) | 同上 | location / { rewrite ^(.*)$ /index.php?s=$1 last; } |
| 多级目录 | /a/b/c 原样进参数 |
用 s=$uri(含完整路径),别用 s=$1 |
$1 的坑:在正则 location 里写 rewrite ^ /index.php?p=$1 last;,$1 取的是 rewrite 自己的正则捕获(这里 ^ 没有捕获组),结果是 p= 空值;日志里能直接看到 rewritten data: "/index.php", args: "p="(实测)。为什么 :rewrite 的捕获组只来自它自己的第一个参数,location 里那条正则与它无关------把完整正则写进 rewrite 才是唯一可靠写法(第 4 节的 /post/ 就是这么写的)。
内部跳转三件套(error_page + internal + @named):
nginx
location /missing { error_page 404 = @fallback; }
location @fallback { return 200 "named fallback hit\n"; } # 实测 /missing → 200
location /hidden { internal; return 200 "internal ok\n"; } # 外部直连 → 404
internal 放行的来源是内部跳转:error_page、index、try_files、rewrite、X-Accel-Redirect。本篇的灰度池 /canary/ 就靠它挡住外部直连(实验 3)。
3. 指令详解
| 指令 | 默认值 | 上下文 | 说明与坑 |
|---|---|---|---|
rewrite |
--- | server location if |
语法 rewrite 正则 替换 [flag];不写 flag 就继续下一条;循环超过 10 次返回 500 |
return |
--- | server location if |
return 444 断连;return 301 /x 的完整 URL 用 $scheme+$host+listen 端口拼,容器里会丢宿主端口 |
break |
--- | server location if |
在 server 级与 last 无可观测差别(location 匹配本来就在 server 级 rewrite 之后);在 location 级才是「不重匹配」 |
if |
--- | server location |
只有 return/rewrite 可靠;proxy_set_header 直接 -t 失败,add_header 会丢外层配置 |
rewrite_log |
off |
http server location if |
日志级别是 notice :error_log ... warn 下永远看不到,改成 notice 才出 rewritten data: |
server_name |
"" |
server |
可写多个;$server_name 只取第一个;_ 不是通配符;正则必须 ^+$ |
listen ... default_server |
无 | server |
每个端口只能有一个默认 server,重复标会 emerg a duplicate default server for 0.0.0.0:80;加它之后其它 server 必须靠 server_name 命中,否则被兜底规则吞掉 |
map |
无 | http |
主键/结果都可含变量;hostnames(≥1.11.3)支持 *.x;volatile(≥1.11.7)关掉缓存 |
geo |
无 | http |
只吃 $remote_addr;支持 CIDR 与 ranges/proxy 参数 |
error_page |
无 | http server location if |
= @name 走命名 location;=200 之类会改写状态码,只写 = 表示沿用原状态码 |
internal |
无 | location |
外部直连返回 404;配合 error_page/rewrite 做「只允许内部到达」的资源 |
try_files |
无 | server location |
最后一项是 URI 或 =404;与 alias 组合有坑(第 4 篇) |
absolute_redirect |
on |
http server location |
≥1.11.8 ;设 off 后 Location 头输出相对路径,容器/反代后面能避开端口拼错 |
4. 完整配置示例
整份替换 /etc/nginx/lab/nginx.conf(已通过 nginx -t,并在 lab 栈里跑通第 5 节全部实验):
nginx
user nginx;
worker_processes 1;
# rewrite_log 的日志是 notice 级:error_log 停在 warn 就永远看不到它
error_log /var/log/nginx/lab_error.log notice;
pid /var/run/nginx.pid;
events { worker_connections 1024; }
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user "$request" $status $body_bytes_sent '
'rt=$request_time urt=$upstream_response_time up=$upstream_addr '
'xff="$http_x_forwarded_for"';
access_log /var/log/nginx/lab_access.log main;
sendfile on;
keepalive_timeout 65;
gzip on; # 与 lab 一致
gzip_types text/css application/javascript application/json text/plain;
resolver 127.0.0.11 valid=5s ipv6=off;
upstream app_pool { # 稳定池:lab 原有三个后端
zone app_pool 64k;
server app1:8080 resolve max_fails=3 fail_timeout=10s;
server app2:8080 resolve max_fails=3 fail_timeout=10s;
server app3:8080 resolve max_fails=3 fail_timeout=10s;
}
upstream app_canary { # 灰度池:实验里成员复用 app3
zone app_canary 64k; # resolve 必须配 zone,否则 -t 直接 emerg
server app3:8080 resolve max_fails=3 fail_timeout=10s;
}
# ---------- 下面四条都只能放 http 上下文 ----------
rewrite_log on; # 调试期打开,上线前关掉
map $http_user_agent $is_canary { # 1) 灰度开关:替代 if
default 0;
~*Android 1;
~*iPhone 1;
}
map $host $host_ok { # 2) 跳转白名单:$host 来自请求头
default 0;
lab.local 1;
localhost 1;
127.0.0.1 1;
}
map $uri $legacy_target { # 3) 旧链接表:命中才有值
default "";
/old/post/2023 /post/2023;
~^/old/tag/(?<tag>[a-z]+)$ /tag/$tag;
}
geo $lan { # 4) IP 段判断:按 $remote_addr
default 0;
127.0.0.0/8 1;
172.16.0.0/12 1;
}
# ---------- 兜底 server:扫描流量直接断连 ----------
server {
listen 80 default_server;
server_name _;
return 444;
}
# ---------- 主站 ----------
server {
listen 80;
server_name lab.local www.lab.local localhost 127.0.0.1;
root /usr/share/nginx/html;
index index.html;
location = /healthz { access_log off; return 200 "gateway ok\n"; }
location /nginx_status { stub_status; allow 127.0.0.1; deny all; }
# 伪静态:/post/123 → /index.php?p=123($1 来自 rewrite 自己的正则)
location ~ ^/post/(\d+)$ {
rewrite ^/post/(\d+)$ /index.php?p=$1 last;
}
location ~ ^/index\.php$ { # lab 没有 PHP,丢给 app_pool 只为看 URI
proxy_pass http://app_pool;
proxy_set_header Host $host;
}
# 灰度:一个 proxy_pass + map,避免在 if 里写 proxy_pass
location /gray/ {
if ($is_canary = 1) { rewrite ^/gray/(.*)$ /canary/$1 last; }
proxy_pass http://app_pool/;
proxy_set_header Host $host;
}
location /canary/ { # 只允许内部跳转进入
internal;
proxy_pass http://app_canary/;
proxy_set_header Host $host;
}
# 旧链接:查表命中 301,未命中 404(不留 302 链)
location /old/ {
if ($legacy_target = "") { return 404; }
return 301 $legacy_target;
}
# 安全跳转:Host 不在白名单直接断连,杜绝开放重定向
location = /jump {
if ($host_ok = 0) { return 444; }
return 301 https://$host$request_uri;
}
location /whoami {
return 200 "host=$host server_name=$server_name lan=$lan canary=$is_canary\n";
}
location /static/ { # 第 4 篇:静态长缓存
alias /usr/share/nginx/html/; expires 7d; add_header Cache-Control "public";
}
location /api/ { # 第 5 篇:带 URI 的反代,前缀被替换
proxy_pass http://app_pool/;
proxy_connect_timeout 2s;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /slow/ { # 第 5 篇:不带 URI,原样透传
proxy_pass http://app_pool; proxy_set_header Host $host; proxy_read_timeout 5s;
}
location / { try_files $uri $uri/ /index.html; }
}
# ---------- 正则 server_name:一套 *.dev.local 测试环境 ----------
server {
listen 80;
server_name ~^(?<devhost>[a-z0-9-]+)\.dev\.local$; # ^ 与 $ 都要写
return 200 "dev host=$devhost host=$host server_name=$server_name\n";
}
}
相对 lab/00-env 改了这 6 处,其余保持原样:
| 位置 | lab 原值 | 本篇值 | 为什么 |
|---|---|---|---|
error_log 级别 |
warn |
notice |
rewrite_log 的日志是 notice 级,warn 下一条都看不到 |
http 段新增 |
无 | rewrite_log on + 2 个 map + 1 个 geo |
用查表替代 if |
upstream |
只有 app_pool |
增加 app_canary(成员 app3:8080) |
灰度池;zone 不能省 |
| 站点定义 | conf.d/default.conf 一个 server,server_name _ |
主配置内 3 个 server:兜底 444 / 主站 / *.dev.local |
多域名与兜底必须写在同处 |
server_name |
_ |
lab.local www.lab.local localhost 127.0.0.1 |
保留 localhost,其余篇的 curl localhost:8080/... 才不会撞上 444 |
| 新增 location | --- | /post/、/gray/、/canary/、/old/、/jump、/whoami |
第 5 节的实验入口 |
本篇把站点配置并进主配置,所以
nginx/conf.d/default.conf要清空(留一行注释即可),否则同一端口会多出一个抢server_name的 server。改完照旧三步:nginx -t -c /etc/nginx/lab/nginx.conf→nginx -s reload→curl验证。
5. 必做实验
实验 1:伪静态 + 亲手造一个 500
bash
curl -s localhost:8080/post/123 # app=app1 / path=/index.php?p=123
# 临时加一条自己重写自己的规则
# location /loop/ { rewrite ^/loop/(.*)$ /loop/$1 last; }
curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/loop/x # 500
docker compose exec -T gateway grep cycle /var/log/nginx/lab_error.log | tail -1
预期日志(实测):
text
[error] ... *93 rewrite or internal redirection cycle while processing "/loop/x", ...
[notice] ... *93 "^/loop/(.*)$" matches "/loop/x", ... # 同样两行会重复 10 次
[notice] ... *93 rewritten data: "/index.php", args: "p=123", ...
为什么是这个结果 :URI 每轮都被改写,nginx 回到 location 匹配又命中同一个 location,循环 10 次后放弃并返回 500。看到这条日志就直接怀疑「规则改写出来的路径又被同一条规则命中」;rewrite_log on + error_log notice 能把每一轮的 matches 与 rewritten data 都打出来,这是调 rewrite 唯一高效的手段。
实验 2:last vs break
nginx
location /v1/ { rewrite ^/v1/(.*)$ /api/$1 last; } # 改完重新匹配 → 命中 /api/
location /v2/ { rewrite ^/v2/(.*)$ /api/$1 break; } # 改完留在 /v2/ → 没有内容处理器
bash
curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/v1/json # 200
curl -s localhost:8080/v1/json | grep path # "path": "/json"
curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/v2/json # 404
为什么是这个结果 :break 之后 nginx 停在 /v2/,那里既没有 proxy_pass 也没有 try_files,只能按 root 找静态文件 /usr/share/nginx/html/api/json,找不到就 404。last 则是把改写后的 URI 交回 location 匹配,/api/json 命中带 URI 的 proxy_pass,上游收到 /json。
实验 3:用 map 做 UA 灰度(并挡住外部直连)
bash
curl -s localhost:8080/gray/json | grep app # "app": "app2"(稳定池轮询,名字会变)
curl -s -A 'Mozilla Android' localhost:8080/gray/json | grep app # "app": "app3"(灰度池)
curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/canary/json # 404
curl -s localhost:8080/whoami # host=localhost ... canary=0
为什么是这个结果 :map 先把 UA 折算成 0/1,if 里只做一件被官方认可的事------rewrite 到 /canary/,last 让它重新匹配;/canary/ 带 internal,外部直接访问一律 404,灰度入口只有一个。这条链路里 if 里没有 proxy_pass,所以不会踩 2.3 的坑。灰度要回滚时只改 map 里那两行 ~* 再 reload,不动任何 location------这也是把开关放进 map 而不是直接写进 location 的实际收益。
实验 4:rewrite 与 proxy_pass 的 URI 之争
nginx
location /g1/ { rewrite ^/g1/(.*)$ /json?ori=$1 break; proxy_pass http://app_pool; }
location /g2/ { rewrite ^/g2/(.*)$ /json?ori=$1 break; proxy_pass http://app_pool/; }
location /g3/ { rewrite ^/g3/(.*)$ /v2x/$1 last; }
location /v2x/ { proxy_pass http://app_pool; }
location /g4/ { if ($arg_new = 1) { proxy_pass http://app_pool; } proxy_pass http://app_pool/; }
| 请求 | 上游收到的 path(实测) |
说明 |
|---|---|---|
/g1/a |
/json?ori=a |
break + 不带 URI 的 proxy_pass:原样透传 |
/g2/a |
/json?ori=a |
带 URI 的 proxy_pass 在 break 之后不参与前缀替换 |
/g3/a |
/v2x/a |
last 交给 /v2x/ 处理 |
/g4/json |
/json |
没命中 if,前缀被替换 |
/g4/json?new=1 |
/g4/json?new=1 |
命中 if,URI 原样透传(含 query) |
为什么是这个结果 :proxy_pass http://app_pool/; 的「前缀替换」只在 URI 未被 rewrite 改动时成立;一旦 break 改了 URI,nginx 把改后的 URI 整条发给上游。所以「剥前缀」和「rewrite 改路径」二选一,别叠加。
实验 5:把一条真实 .htaccess 翻译成 nginx
text
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?s=$1 [L,QSA]
nginx
# 写法 A(正解):文件在就直接发,不在就打进入口
location / { try_files $uri $uri/ /index.php?s=$uri; }
# 写法 B(字面翻译):能用,但只在「没有其它 if 需求」时才这样写
location / { if (!-f $request_filename) { rewrite ^ /index.php?s=$uri last; } }
bash
curl -s -o /dev/null -w '%{http_code} %{content_type}\n' localhost:8080/index.html # 200 text/html
curl -s localhost:8080/news/2024 # app=app1 / path=/index.php?s=/news/2024
为什么是这个结果 :两种写法在本例观测结果一致(实测),但语义不同------try_files 是内容阶段的一次性判断,if (!-f ...) 依赖 $request_filename(root+$uri),在 alias、internal 跳转后并不等于真实文件路径。[QSA] 的等效点是原 $args 会被自动带上,要让 ? 丢弃原参数得在 replacement 末尾加 ?(如 /show?user=$1?)。
6. 验收自测(5 题)
Q1. last 与 break 的区别是什么?在 location /x/ 里把 /a/1 改写成 /b/1,两种写法分别发生什么?
答案要点 :两者都停止本轮 rewrite 指令集。last 回到 location 匹配(新 URI 可能落到另一个 location 的内容处理器),break 留在当前 location 直接进内容阶段。实测对照见实验 2:last → 200 且上游收到 /json;break → 404(/v2/ 没内容处理器)。所以「交给另一个 location 处理」用 last,「就地继续用本 location 的 proxy_pass」用 break。
Q2. 为什么在 if 里写 proxy_pass 会出问题?给出两种替代写法。
答案要点 :if 会被实例化成独立的嵌套配置,proxy_pass 在里面的 URI 规则失效------带 URI 的 proxy_pass 变成原样透传(实测 /g4/json?new=1 上游收到 /g4/json?new=1);而且 proxy_set_header 在 if 里直接 -t 报 "proxy_set_header" directive is not allowed here。替代:①map 得值 + 两条 location(本篇 /gray/ + /canary/);②try_files 或 error_page 跳到命名 location。
Q3. server_name 的匹配顺序?为什么 ~\.dev\.local 危险?
答案要点 :精确 → 前导通配(最长)→ 后导通配(最长)→ 正则(按文件顺序取第一个)→ 默认 server(default_server 或该端口第一个)。没写 ^/$ 的正则命中任意包含该子串的 Host,实测 Host: evil.dev.local.attacker.com 直接进了 dev 站;必须写 ~^[a-z0-9-]+\.dev\.local$。
Q4. return 301 https://$host$request_uri; 有什么风险?怎么修?
答案要点 :$host 完全取自请求头,Host: evil.com 就变成开放重定向(实测 301 到 https://evil.com/...),可被用作钓鱼跳板。修法:用 map $host $host_ok 建白名单,不在表里就 return 444(本篇 /jump);或改用 $server_name 固定域名,代价是多域名站点要写多份;容器里还要注意 return 301 /x 的相对 URI 是按 listen 端口补全的,宿主端口会丢,必要时配 absolute_redirect off;(≥1.11.8)。
Q5. 把 .htaccess 的 RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ index.php?s=$1 [L,QSA] 翻译成 nginx,并说明差异。
答案要点 :首选 location / { try_files $uri $uri/ /index.php?s=$uri; };字面翻译是 location / { if (!-f $request_filename) { rewrite ^ /index.php?s=$uri last; } }。差异:try_files 在内容阶段判断、可用 =404/@named,alias 下语义清晰;if (!-f) 依赖 $request_filename,alias/内部跳转后不等于真实路径,且 if 里不能写 proxy_pass/proxy_set_header。[QSA] 的等效点是原 $args 自动保留,要丢弃得在 replacement 末尾写 ?。
7. 常见坑
-
if里proxy_pass后,上游收到整条 URI 。现象:/g4/json?new=1到了后端还是/g4/json?new=1(带前缀带 query)。根因:if的嵌套配置让proxy_pass的前缀替换失效。正解:用map得值 + 两条 location;if里只留return/rewrite。 -
rewrite ... break之后前缀没被剥掉,上游 404 。现象:本想剥/v1/前缀,结果上游收到带前缀的路径。根因:proxy_pass带 URI 的替换只在 URI 未改动时生效。正解:二选一------要剥前缀就让proxy_pass带 URI 且不写 rewrite;要改路径就用不带 URI 的proxy_pass。 -
站点被奇怪域名命中,甚至
evil.dev.local.attacker.com进了内网站 。现象:内网测试站被外部域名访问到。根因:正则server_name忘了^/$,或无兜底 server。正解:加锚定 +listen 80 default_server+return 444兜底。 -
跳转丢
www或丢端口 。现象:www.lab.local被跳到lab.local;容器里跳转 URL 少了:8080。根因:用了$server_name(配置里第一个名字);return 301 /x的端口取 listen 端口(容器内 80,宿主 8080)。正解:用$host并配合白名单;或absolute_redirect off;(≥1.11.8)输出相对 Location。 -
rewrite_log on了但日志里什么都没有 。现象:error_log 里搜不到rewritten data:。根因:error_log级别停在warn,而 rewrite 日志是 notice 级。正解:error_log ... notice;(仅调试期),看完改回warn。 -
-t报"map" directive is not allowed here或resolving names at run time requires upstream ... to be in shared memory。现象:配置一加就起不来。根因:map/geo写进了server;upstream 用resolve却没配zone。正解:map/geo放http;resolve(≥1.27.3)必须与zone同用。 -
加了 444 兜底后,健康检查和 IP 直连全挂 。现象:
curl localhost:8080/healthz被直接断连。根因:兜底 server 抢成了default_server,业务 server 只剩server_name匹配,而Host: localhost不在名单里。正解:业务 server 的server_name里带上localhost/127.0.0.1(本篇就是这么做的)。 -
location ~ ^/post/(\d+)$ { rewrite ^ /index.php?p=$1 last; }结果p=为空 。现象:伪静态跳过去参数是空值。根因:$1取的是rewrite自己的正则捕获(^没有捕获组),不是 location 的正则。正解:把完整正则写进rewrite;用rewrite_log的rewritten data复核。
8. 延伸阅读
| 文档页 | 解决什么问题 |
|---|---|
| ngx_http_rewrite_module | rewrite/return/break/if/rewrite_log 全集与官方示例,are executed sequentially 的原文出处 |
| Server names | server_name 匹配顺序、通配与正则的完整规则 |
| ngx_http_map_module | map 的取值优先级、hostnames、volatile |
| ngx_http_geo_module | geo 的 IP 段写法与 ranges/proxy 参数 |
| ngx_http_core_module | error_page、internal、try_files、absolute_redirect 的官方定义 |
| IfIsEvil | 「if is evil」的官方说明与替代做法,2.3 那张表的依据 |
章节依赖 :本篇依赖第 5 篇的 proxy_pass URI 规则与第 4 篇的 location 匹配顺序(rewrite 改完 URI 只是把选择权交回第 4 篇的规则);本篇的 map 灰度开关与 server_name 白名单会被第 7 篇的负载均衡进阶和第 10 篇的 HTTPS/安全加固直接复用,rewrite 的 $1 捕获与 if 边界在第 15 篇的故障案例里反复出现。
系列导航:第 1 篇进程模型 → 第 2 篇安装升级 → 第 3 篇配置语法 → 第 4 篇静态站与 location → 第 5 篇反向代理 → 第 6 篇(本篇)rewrite 与 server_name → 第 7 篇负载均衡进阶 → 第 8 篇缓存 → 第 9 篇日志排障 → 第 10 篇 HTTPS 与安全 → 第 11 篇 Lua 与 OpenResty → 第 12 篇性能调优 → 第 13 篇高可用架构与网关 → 第 14 篇可观测性与工程化 → 第 15 篇故障案例库