Nginx配置:保留非标准端口跳转及多域名无端口访问
Nginx配置解决方案
核心配置思路
- 单独配置带端口的主域名server块,强制在跳转过程中保留端口号
- 用一个通用server块处理所有无端口的子域名,支持新增域名时无需大幅修改配置
- 反向代理到已监听5555端口的应用服务
具体配置代码
1. 带端口主域名的处理配置
# 处理带端口的主域名请求,确保跳转时保留5555端口 server { listen 443 ssl; server_name app1.company.com; # 替换为你的SSL证书路径 ssl_certificate /path/to/your/app1-cert.pem; ssl_certificate_key /path/to/your/app1-key.pem; # 强制传递带端口的Host头给后端应用 set $target_port 5555; proxy_set_header Host $host:$target_port; proxy_set_header X-Forwarded-For $remote_addr; location / { proxy_pass https://localhost:5555; # 修正后端返回的重定向地址,确保跳转后仍带端口 proxy_redirect https://$host https://$host:$target_port; proxy_redirect http://$host http://$host:$target_port; } }
2. 无端口子域名的通用处理配置
# 处理所有无端口的子域名请求,支持新增域名直接添加到server_name server { listen 443 ssl; # 可使用通配符(如*.company.com)自动匹配所有子域名,或明确列举需要的域名 server_name dev-app1.company.com test-app1.company.com *.company.com; # 替换为你的通配符SSL证书路径(若使用精确域名则对应单独证书) ssl_certificate /path/to/your/wildcard-company-cert.pem; ssl_certificate_key /path/to/your/wildcard-company-key.pem; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; location / { proxy_pass https://localhost:5555; # 修正后端返回的重定向地址,适配当前子域名(无端口) proxy_redirect https://localhost:5555 https://$host; proxy_redirect http://localhost:5555 http://$host; } }
关键配置说明
- 端口保留机制:主域名配置中,通过
proxy_set_header Host $host:$target_port让后端应用感知到带端口的请求源,同时proxy_redirect会把后端返回的不带端口的跳转URL替换为带端口的,彻底解决跳转丢端口的问题。 - 域名扩展性:如果使用
*.company.com作为server_name,新增类似stage-app1.company.com的域名时,只需将域名解析到Nginx服务器即可,无需修改配置;若需精确控制,直接在server_name后追加域名即可。 - SSL证书匹配:主域名使用单域名证书,子域名单独配置或使用通配符证书,确保HTTPS请求正常加密。
- 应用端配合:确保应用已正确监听5555端口,并且能够处理Nginx传递的
Host和X-Forwarded-For头,避免出现路径或来源识别错误。
内容的提问来源于stack exchange,提问作者uberrebu
相关产品推荐
相关产品推荐

