Nginx二级目录反向代理网站

场景:
  • 名A下面通过二级目录来匹配不同隐式代理的域名。
    server {
        listen 80;
        server_name dev-we-show.fonzie.com;
        location / {
             #index index.html index.htm;
             #root html/;
             #proxy_next_upstream http_502 http_504 error timeout invalid_header;
             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_pass http://dev_b;
             expires      -1;
             proxy_connect_timeout 300;
            proxy_send_timeout 300;
            proxy_read_timeout 300;
    
           #rewrite (.*)/wapindex(.*) /vperson$1/wapindex$2;
           #rewrite (.*)/image(.*) /vperson$1/image$2;
           #rewrite (.*)/js(.*) /vperson$1/js$2;
    }
    
        location /vperson/ {
           proxy_pass https://www.vperson.com/;
        }
    
    }
    • 通过域名dev-we-show.fonzie.com/vperson/,nginx会匹配到反向代理为https://www.vperson.com/的域名上去,因为使用的是绝对引用,这里如果使用相对应用会使https://www.vperson.com/域名变成https://www.vperson.com/vperson/最终访问失败。https://www.vperson.com的首页为:https://vperson.com/wapindex.但是域名dev-we-show.fonzie.com的根下面没有路径wapindex。
    • 所以这里需要使用重定向进行替换,匹配路径为/,打开上面的井号内容,如下:
    server {
        listen 80;
        server_name dev-we-show.fonzie.com;
        location / {
             #index index.html index.htm;
             #root html/;
             #proxy_next_upstream http_502 http_504 error timeout invalid_header;
             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_pass http://dev_b;
             expires      -1;
             proxy_connect_timeout 300;
            proxy_send_timeout 300;
            proxy_read_timeout 300;
    
           rewrite (.*)/wapindex(.*) /vperson$1/wapindex$2;
           rewrite (.*)/image(.*) /vperson$1/image$2;
           rewrite (.*)/js(.*) /vperson$1/js$2;
    }
        location /vperson/ {
           proxy_pass https://www.vperson.com/;
        }
    
    }
    这样一来在反向代理的时候,用户首先通过dev-we-show.fonzie.com/vperson/访问这台nginx,再通过这台nginx反向代理到https://www.vperson.com/,但这个跳转是隐式的,所以在浏览器的地址栏还是dev-we-show.fonzie.com,问题在于dev-we-show.fonzie.com下面并没有/wapindex的路径,所以我们需要在根/下面添加rewrite通过正则匹配修改,并添加以后路径,然他回去的时候依然是走dev-we-show.fonzie.com/vperson/的路径,而不是dev-we-show.fonzie.com的路径。

    作者:Fonzie
    链接:https://www.jianshu.com/p/728409ad09a0

为您推荐