Nginx 中二级域名重定向需区分跳转(permanent/redirect)与内部重写(last/break),通过 server_name 正则提取子域名,配合 rewrite 或 return 实现地址栏变更或路径映射,并注意 proxy_set_header Host 和 HTTPS 统一处理。

二级域名重定向在 Nginx 中主要靠 rewrite 指令配合 server_name 和变量提取实现,关键在于区分“内部重写”和“客户端跳转”,并正确使用标志位(permanent 或 redirect)来控制浏览器地址栏是否变化。
明确目标类型:跳转还是重写?
先确认你要的是:
-
301/302 跳转(浏览器地址栏变):比如访问
blog.example.com自动跳到example.com/blog/;用permanent或redirect标志。 -
内部路径重写(地址栏不变,仅服务端处理):比如
api.example.com/v1/users实际转发到后端/v1/users;用last或break,通常搭配proxy_pass。
常见二级域名跳转配置(带变量提取)
以 abc.example.com → example.com/test/abc/ 为例:
server {
listen 80;
server_name ~^(?<subdomain>.+)\.example\.com$;
<pre class="brush:php;toolbar:false;"># 提取子域名,跳转到主站对应路径
rewrite ^(.*)$ https://example.com/test/$subdomain/$1 permanent;
}
说明:
-
~^...启用正则匹配server_name,(?<subdomain>.+)</subdomain>是命名捕获组,值存入变量$subdomain。 -
$1是原始请求路径(如/post/123),保留完整路径结构。 -
permanent发送 301,适合生产环境;测试时可换redirect(302)。
不改变地址栏的二级域名路由(内部重写)
比如 admin.example.com 的所有请求,都映射到主站 /admin/ 下处理:
server {
listen 80;
server_name admin.example.com;
<pre class="brush:php;toolbar:false;">location / {
# 把 /xxx 重写为 /admin/xxx,不跳出当前 location
rewrite ^/(.*)$ /admin/$1 break;
proxy_pass http://backend;
proxy_set_header Host example.com;
}}
注意:
-
break阻止后续 rewrite 执行,且不重新匹配 location;适合简单前缀追加。 - 若需重匹配 location(例如重写后路径匹配另一个
location ~ \.php$),改用last。 - 务必配
proxy_set_header Host,避免后端收到错误的 host 头。
HTTPS + 二级域名统一跳转(推荐组合)
强制跳转到 HTTPS 主域名,并保留子域名逻辑:
server {
listen 80;
server_name ~^(?<subdomain>.+)\.example\.com$;
return 301 https://example.com/test/$subdomain$request_uri;
}
<p>server {
listen 443 ssl;
server_name example.com;</p>
<h1>SSL 配置省略...</h1>
<pre class="brush:php;toolbar:false;">location /test/ {
root /var/www;
index index.html;
}
}
优势:
- 用
return替代rewrite更高效、更安全(if在 location 外慎用,return无此风险)。 -
$request_uri完整保留路径+查询参数,比$1更可靠。 - SSL 终止放在独立 server 块,职责清晰。











