关于java:Nginx系列转发请求的方法

8次阅读

共计 1587 个字符,预计需要花费 4 分钟才能阅读完成。

原文网址:​​Nginx 系列 – 转发申请的办法_IT 利刃出鞘的博客 -CSDN 博客​​

简介

阐明

本文介绍 Nginx 转发申请的办法。

分享 Java 技术星球(自学精灵):​​https://learn.skyofit.com/​​

需要

用户拜访 aaa.com/bbb 时,理论拜访的是 bbb123.com。

计划 1:return

办法

server {
    listen       8080;
    server_name  aaa.com;

    location /bbb {return 302 https://bbb123.com$request_uri;} 
}

![]()

阐明

浏览器会间接跳转到 https://bbb123.com,相当于间接 location.href =‘https://bbb123.com’。

计划 2:rewrite

办法

法 1:正则匹配所有的 URI 再去掉结尾第一个 /(反斜线)。

server {
    listen       80;
    server_name  aaa.com;
    rewrite ^/(.*)$ https://bbb123.com/$1 permanent;
}

法 2:$request_uri 变量匹配所有的 URI。

server {
    listen       80;
    server_name  aaa.com;
    rewrite ^ https://bbb123.com$request_uri? permanent;
}

法 3:与 if 联合

server {
    listen       80;
    server_name  aaa.com abc.com;
    if ($host = 'aaa.com') {rewrite ^/(.*)$ https://bbb123.com/$1 permanent;
    }
}

阐明

浏览器会间接跳转到 https://bbb123.com,相当于间接 location.href =‘https://bbb123.com’。

计划 3:proxy_pass

办法

server {
    listen       80;
    server_name  aaa.com;
  
    location /aaa/ {proxy_pass https://bbb123.com;}
}

阐明

浏览器显示的依然是 aaa.com/aaa,用户是不晓得 https://bbb123.com 的存在的。

联结应用

上边三者是能够联结应用的,例如:

例 1:rewrite 带 break

server {
    listen       80;
    server_name  localhost;
    
    location /abc {
        # 只保留 /abc/ 前面的门路
        rewrite ^/abc/(.*)$ /proxy/$1 break;
        # 改写完之后, 再进行代理; 最终后果: http://www.proxy_pass.com/proxy/$1 
        proxy_pass http://www.proxy_pass.com;
    }
 
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm index.php;
    }
}

拜访:localhost/abc/aaa

理论拜访:http://www.proxy_pass.com/abc/aaa(用户无感知)

例 2:rewrite 不带 break

server {
    listen       80;
    server_name  localhost;
    
    location /abc {
        # 只保留 /abc/ 前面的门路
        rewrite ^/abc/(.*)$ /proxy/$1;
        # 改写完之后, 再进行代理; 最终后果: http://www.proxy_pass.com/proxy/$1 
        proxy_pass http://www.proxy_pass.com;
    }
 
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm index.php;
    }
}

拜访:localhost/abc/aaa

理论拜访:/usr/share/nginx/html/index.html(用户无感知)

正文完
 0