You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx动态路径重写实现Next.js多域名无跳转路径前缀添加

解决方案

核心修改如下:

  • 修正原配置语法错误:补全location /static块缺失的闭合花括号
  • 将根路径location /下的硬编码域名判断替换为动态匹配$host的正则,自动适配所有绑定的域名
  • 保留rewrite的break标识,仅执行Nginx内部转发,不触发客户端跳转,地址栏URL不会发生变化

修改后的完整配置:

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=STATIC:10m inactive=7d use_temp_path=off;

upstream nextjs_upstream {
  server 127.0.0.1:3000;
}

server {
  listen 80;

  # 可继续添加域名,如需匹配所有绑定到当前服务器的域名,直接改为 server_name _;
  server_name a.com b.com;

  server_tokens off;

  gzip on;
  gzip_proxied any;
  gzip_comp_level 4;
  gzip_types text/css application/javascript image/svg+xml;

  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection 'upgrade';
  proxy_set_header Host $host;
  proxy_cache_bypass $http_upgrade;

  location /_next/static {
    proxy_cache STATIC;
    proxy_pass http://nextjs_upstream;

    # 生产环境可删除以下缓存调试头
    add_header X-Cache-Status $upstream_cache_status;
  }

  location /static {
    proxy_cache STATIC;
    proxy_ignore_headers Cache-Control;
    proxy_cache_valid 60m;
    proxy_pass http://nextjs_upstream;
    add_header X-Cache-Status $upstream_cache_status;
  }

  location / {
    # 仅当路径开头不是当前域名时执行重写
    if ($request_uri !~* "^/$host(/.*|$)") {
        add_header X-see "special";
        rewrite (.*) /$host$1 break;
    }

    proxy_pass http://nextjs_upstream;
  }
}

内容的提问来源于stack exchange,提问作者Amir Saadallah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:48:02