详解proxy_pass根据path路径转发时的"/"问题记录

2019-10-17 17:22:59于海丽

如下配置,想要实现的需求:

192.168.1.27是后端的real server,8080端口是公司的ehr人事系统端口。

又由于该系统涉及到微信接口访问,即http://ehr.wang.com/attendance和http://ehr.wang.com/app

由于是内部系统,安全考虑,所以要求:

1)登录ehr人事系统的时候要求使用内网登录,即http://192.168.1.27:8080,访问前要先登录公司VPN
2)登录微信接口http://ehr.wang.com/attendance和http://ehr.wang.com/app使用外网登录,即使用解析后域名登录。
3)访问http://ehr.wang.com,强制跳转为https://ehr.wang.com/attendance

[root@BJLX_4_21_P vhosts]# cat ehr.conf
server {
  listen 80;
  server_name ehr.wang.com;
  
  access_log logs/ehr_access.log;
  error_log  logs/ehr_error.log;
 
  return   301 https://$server_name$request_uri;   
}
 
[root@BJLX_4_21_P vhosts]# cat ssl-ehr.conf
upstream ehr {
  server 192.168.1.27:8080 max_fails=3 fail_timeout=30s;
}
 
server {
  listen 443;
  server_name ehr.wang.com;
  ssl on;
 
  ### SSL log files ###
  access_log logs/ehr_access.log;
  error_log logs/ehr_error.log;
 
### SSL cert files ###
  ssl_certificate ssl/wang.cer;   
  ssl_certificate_key ssl/wang.key; 
  #ssl_session_timeout 5m;
 
  location / {
    return 301 https://ehr.wang.com/attendance;
  }
 
  location /attendance/ {
  proxy_pass http://ehr;
  proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
  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 https;
  #proxy_set_header X-Forwarded-Proto https;
  proxy_redirect off;
  }
 
  location /app/ {
  proxy_pass http://ehr;
  proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
  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 https;
  #proxy_set_header X-Forwarded-Proto https;
  proxy_redirect off;
  }
 }

注意:

由于从浏览器访问(http)到源站的real server之间要经过Nginx反向代理层(https)

需要将proxy_set_header X-Forwarded-Proto https;这一行注释掉,否则上面的配置无效。

如果中间没有代理层,直接是在real server本机进行nginx的反向代理(即本机nginx反代到本机的8080端口),则这个参数无效注释(已经过验证)

HTTP头域(proxy_set_header)列表与解释

HTTP 头域是HTTP协议中请求(request)和响应(response)中的头部信息,其实就是HTTP通信的操作参数,告诉web服务器和浏览器怎样处理这个通信。

HTTP头从一个请求信息或者响应信息的第二行开始(第一行是请求行或者响应行),以两个CR-LF字符组结束(CR:回车符,r,LF:换行符n)