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

Nginx反向代理配置求助:实现Next.js应用无端口访问

Next.js 应用 Nginx 反向代理配置问题修复

问题描述

我的服务器上运行着一个 Next.js 应用,部署在 https://localhost:3000,可通过 https://rgb.irpsc.com:3000/citizen/hm-2000001 访问(其中 hm-2000001 是动态参数,范围从 hm-2000000 到任意值)。希望用户无需指定端口,输入 https://rgb.irpsc.com/citizen/hm-2000003 就能访问对应页面,但已配置的 Nginx 规则未生效,当前配置如下:

location /citizen {
    proxy_pass https://localhost:3000/citizen;
}

修复方案

完整 Nginx 配置示例

server {
    listen 443 ssl;
    server_name rgb.irpsc.com;

    # 替换为你的 SSL 证书路径
    ssl_certificate /path/to/your/certificate.crt;
    ssl_certificate_key /path/to/your/private.key;

    location /citizen {
        proxy_pass https://localhost:3000;
        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;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

# 可选:将 HTTP 请求强制重定向到 HTTPS
server {
    listen 80;
    server_name rgb.irpsc.com;
    return 301 https://$host$request_uri;
}

关键调整说明

  1. 修正代理路径:原配置中 proxy_pass 后的 /citizen 会导致请求路径被重复拼接(变成 https://localhost:3000/citizen/citizen/xxx),去掉该路径后,Nginx 会将完整的请求路径(如 /citizen/hm-2000003)转发给 Next.js 应用。
  2. 添加代理头信息:Next.js 依赖 Host、X-Forwarded-Proto 等头信息正确处理路由和服务端渲染,缺少这些可能导致页面跳转或资源加载失败。
  3. 配置 HTTPS 监听:默认 HTTPS 端口为 443,必须在 server 块中声明 listen 443 ssl 并配置有效 SSL 证书,才能实现无端口访问。

内容的提问来源于stack exchange,提问作者Abbas Ajorlou

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:35:12