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

如何将访问sub.example.com的请求转发至example.com:8082(Nginx代理Apache场景)

实现Nginx代理sub.example.com到example.com:8082的配置方案

没问题,这是Nginx反向代理的常规操作,我帮你梳理具体步骤,保证能搞定:

1. 准备工作

首先确保你的Nginx已经正常安装并运行,同时确认example.com:8082这个服务能在服务器本地正常访问(可以用curl http://example.com:8082测试)。另外记得把sub.example.com的DNS解析指向你的服务器公网IP,不然用户访问子域名时找不到你的服务器。

2. 编辑Nginx配置文件

找到Nginx的配置目录,通常是/etc/nginx/sites-available/,在里面新建一个配置文件(比如sub.example.com.conf),或者直接编辑默认的default.conf文件,添加以下server块:

server {
    listen 80;
    server_name sub.example.com;

    location / {
        # 把请求转发到目标服务地址
        proxy_pass http://example.com:8082;
        
        # 传递必要的请求头,让后端服务能正确识别请求来源
        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;
    }
}

配置说明:

  • listen 80:监听80端口(HTTP默认端口)
  • server_name sub.example.com:指定这个server块处理的域名
  • proxy_pass:核心指令,把请求转发到目标服务的地址
  • 那些proxy_set_header:用来传递请求的原始信息,比如客户端IP、请求协议等,很多后端服务依赖这些头来正确处理请求

3. 启用配置并验证

  • 如果是新建的配置文件,需要在/etc/nginx/sites-enabled/目录下创建软链接启用它:
    ln -s /etc/nginx/sites-available/sub.example.com.conf /etc/nginx/sites-enabled/
    
  • 测试配置文件是否有语法错误:
    nginx -t
    
    如果输出nginx: configuration file /etc/nginx/nginx.conf test is successful就说明没问题。
  • 重启Nginx让配置生效:
    systemctl restart nginx
    # 或者用 service nginx restart(取决于你的系统)
    

4. 可选:配置HTTPS(如果需要)

如果想要给sub.example.com配置HTTPS,可以用Let's Encrypt免费证书,配置后server块大概是这样:

server {
    listen 443 ssl;
    server_name sub.example.com;

    ssl_certificate /path/to/your/cert.pem;
    ssl_certificate_key /path/to/your/privkey.pem;

    location / {
        proxy_pass http://example.com:8082;
        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;
    }
}

# 把HTTP请求重定向到HTTPS
server {
    listen 80;
    server_name sub.example.com;
    return 301 https://$host$request_uri;
}

这样配置完成后,用户访问sub.example.com就会被Nginx转发到example.com:8082的服务了。

内容的提问来源于stack exchange,提问作者Anders Yuran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:20:38