一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

二级域名重定向时 Nginx URL 重写如何配

时间:2026-08-08 13:15:06 编辑:袖梨 来源:一聚教程网

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

二级域名重定向在 Nginx 中主要靠 rewrite 指令配合 server_name 和变量提取实现,关键在于区分“内部重写”和“客户端跳转”,并正确使用标志位(permanentredirect)来控制浏览器地址栏是否变化。

明确目标类型:跳转还是重写?

先确认你要的是:

  1. 301/302 跳转(浏览器地址栏变):比如访问 blog.example.com 自动跳到 example.com/blog/;用 permanentredirect 标志。
  2. 内部路径重写(地址栏不变,仅服务端处理):比如 api.example.com/v1/users 实际转发到后端 /v1/users;用 lastbreak,通常搭配 proxy_pass

常见二级域名跳转配置(带变量提取)

abc.example.com → example.com/test/abc/ 为例:

server {listen 80;server_name ~^(?.+).example.com$;
# 提取子域名,跳转到主站对应路径rewrite ^(.*)$ https://example.com/test/$subdomain/$1 permanent;

}

说明:

  1. ~^... 启用正则匹配 server_name(?.+) 是命名捕获组,值存入变量 $subdomain
  2. $1 是原始请求路径(如 /post/123),保留完整路径结构。
  3. permanent 发送 301,适合生产环境;测试时可换 redirect(302)。

不改变地址栏的二级域名路由(内部重写)

比如 admin.example.com 的所有请求,都映射到主站 /admin/ 下处理:

server {listen 80;server_name admin.example.com;
location / {# 把 /xxx 重写为 /admin/xxx,不跳出当前 locationrewrite ^/(.*)$ /admin/$1 break;proxy_pass http://backend;proxy_set_header Host example.com;}

}

注意:

  1. break 阻止后续 rewrite 执行,且不重新匹配 location;适合简单前缀追加。
  2. 若需重匹配 location(例如重写后路径匹配另一个 location ~ .php$),改用 last
  3. 务必配 proxy_set_header Host,避免后端收到错误的 host 头。

HTTPS + 二级域名统一跳转(推荐组合)

强制跳转到 HTTPS 主域名,并保留子域名逻辑:

server {listen 80;server_name ~^(?.+).example.com$;return 301 https://example.com/test/$subdomain$request_uri;}

server { listen 443 ssl; server_name example.com;

SSL 配置省略...
location /test/ {root /var/www;index index.html;}

}

优势:

  1. return 替代 rewrite 更高效、更安全(if 在 location 外慎用,return 无此风险)。
  2. $request_uri 完整保留路径+查询参数,比 $1 更可靠。
  3. SSL 终止放在独立 server 块,职责清晰。

热门栏目