Nginx二级目录反向代理网站

参考https://www.jianshu.com/p/728409ad09a0?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

场景:

域名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 的路径。

链接:https://www.jianshu.com/p/728409ad09a0
来源:简书

发布了30 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/djfjkj52/article/details/96426979