如何在Nginx中根据Host头将请求proxy pass至指定IP?
Nginx基于Host头的代理转发配置方法
要实现请求Host头为test1.example.com时转发到指定IP,只需要在Nginx配置中添加精确匹配该Host的server块即可,具体步骤如下:
编辑Nginx配置文件
打开Nginx的主配置文件(通常是/etc/nginx/nginx.conf),或者在/etc/nginx/conf.d/目录下新建一个自定义配置文件(比如test-proxy.conf),避免修改主配置文件影响其他服务。添加匹配Host的代理配置
根据你的HTTP/HTTPS需求选择对应配置:HTTP请求配置
server { listen 80; # 精确匹配目标Host头 server_name test1.example.com; location / { # 替换为你需要转发的特定IP地址 proxy_pass http://192.168.1.100; # 可选:设置代理请求头,保留原请求信息 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; } }HTTPS请求配置(如需支持HTTPS)
server { listen 443 ssl; server_name test1.example.com; # 配置SSL证书路径 ssl_certificate /path/to/your/ssl/cert.pem; ssl_certificate_key /path/to/your/ssl/private.key; location / { proxy_pass http://192.168.1.100; 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; } }验证配置并重启Nginx
- 执行
nginx -t检查配置语法,输出nginx: configuration file /etc/nginx/nginx.conf test is successful即为正常。 - 重启Nginx服务使配置生效:
- Systemd系统:
systemctl restart nginx - SysVinit系统:
service nginx restart
- Systemd系统:
- 执行
补充说明
server_name支持精确匹配、通配符匹配(如*.example.com)和正则匹配,这里的精确匹配刚好符合你的需求。- 若需同时匹配多个Host,可在
server_name后用空格分隔多个域名,比如server_name test1.example.com test2.example.com;。
内容的提问来源于stack exchange,提问作者user19641386
相关产品推荐
相关产品推荐

