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
相关产品推荐
相关产品推荐

