nginx proxy_redirect https配置后端http302跳转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | # HTTPS server # server { listen 443 ssl; server_name localhost; charset utf8; ssl_certificate full_chain.pem; ssl_certificate_key private.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; 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_connect_timeout 10; proxy_send_timeout 90; proxy_read_timeout 90; proxy_redirect http: // $host/ https: // $host:$server_port/; location /mgr/ { proxy_pass http: //localhost :8080 /mgr/ ; } } |
nginx使用proxy_redirect替换proxy_pass Response 301/302的Location字段
Nginx通过proxy_pass反向代理请求到任意一个地址,并将Response返回给用户,多数情况下这是没什么问题的,但有一种情况下需要额外处理301/302的Location字段,假设
- Server: 192.168.1.2: 是内网中的一台服务,在内网环境中大家都直接访问它
- Nginx: 192.168.1.3: 是一台外网入口的Nginx服务,访问外网IP将直接访问到它,它会反向代理到192.168.1.2
192.168.1.3 nginx.conf
1 2 3 4 5 6 7 8 | server { listen80; server_name www.iisp.com; location / { proxy_pass http: //192 .168.1.2; } } |
可是通过外网用户通过域名www.iisp.com通过Nginx代理服务器反向代理内网服务时Server在Response 301/302的Location会写内网IP,如:
1 2 3 4 5 6 7 | $ curl -I http: //www .iisp.com/ HTTP /1 .1 302 Server: nginx /1 .16.0 Date: Tue, 26 Nov 2019 08:00:35 GMT Location: http: //192 .168.1.2 /index .html Connection: keep-alive Cache-Control: no-cache |
外网用户被Location到一个内网地址192.168.1.2自然访问不到,因为不是在内网环境。
这个时候我们需要配置一下Nginx的反向代理设置,通过添加一条proxy_redirect指令替换Server响应301/302 Location字段,配置如下:
1 2 3 4 5 6 7 8 9 | server { listen80; server_name www.iisp.com; location / { proxy_pass http: //192 .168.1.2; proxy_redirect http: //192 .168.1.2 http: //www .iisp.comwww.iisp.com; } } |
保存重启Nginx服务,此时再来测试一下,外网测试入口www.iisp.com:
1 2 3 4 5 6 7 | $ curl -I http: //www .qttc.net/ HTTP /1 .1 302 Server: nginx /1 .16.0 Date: Tue, 26 Nov 2019 08:31:45 GMT Location: http: //www .qttc.net /index .html Connection: keep-alive Cache-Control: no-cache |
从上面的信息可以看到从外网访问时Server服务response的header信息中,已经在Nginx反向代理那一段替换了Location字段的协议、域名和端口部分,这样的话外网用户最终得到的302地址是一个外网地址从而可以跳转网页
而内网用户因为直接访问Server服务,不经过Nginx代理,自然也不会受影响,内网测试入口192.168.1.2:
1 2 3 4 5 6 7 | $ curl -I http: //192 .168.1.2/ HTTP /1 .1 302 Server: nginx /1 .16.0 Date: Tue, 26 Nov 2019 09:10:33 GMT Location: http: //192 .168.1.2 /index .html Connection: keep-alive Cache-Control: no-cache |
通过额外部署一个Nginx并利用proxy_redirect指令配合proxy_pass反向代理解决了内外网不同IP/域名访问服务的问题。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。