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

原文网址:​​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(用户无感知)

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理