Nginx系列--转发请求的方法

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

简介

说明

本文介绍Nginx转发请求的方法。

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

需求

用户访问aaa.com/bbb时,实际访问的是bbb123.com。

方案1:return

方法

bash 复制代码
server {
    listen       8080;
    server_name  aaa.com;

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

说明

浏览器会直接跳转到bbb123.com,相当于直接location.href = 'bbb123.com'

方案2:rewrite

方法

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

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

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

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

法3:与if结合

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

说明

浏览器会直接跳转到bbb123.com,相当于直接location.href = 'bbb123.com'

方案3:proxy_pass

方法

ini 复制代码
server {
    listen       80;
    server_name  aaa.com;
  
    location /aaa/ {
        proxy_pass https://bbb123.com;
    }
}

说明

浏览器显示的仍然是aaa.com/aaa,用户是不知道bbb123.com的存在的。

联合使用

上边三者是可以联合使用的,例如:

例1:rewrite带break

bash 复制代码
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

bash 复制代码
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(用户无感知)

相关推荐
追逐时光者5 小时前
推荐 12 款开源美观、简单易用的 WPF UI 控件库,让 WPF 应用界面焕然一新!
后端·.net
Jagger_5 小时前
敏捷开发流程-精简版
前端·后端
苏打水com6 小时前
数据库进阶实战:从性能优化到分布式架构的核心突破
数据库·后端
间彧7 小时前
Spring Cloud Gateway与Kong或Nginx等API网关相比有哪些优劣势?
后端
间彧7 小时前
如何基于Spring Cloud Gateway实现灰度发布的具体配置示例?
后端
间彧7 小时前
在实际项目中如何设计一个高可用的Spring Cloud Gateway集群?
后端
间彧7 小时前
如何为Spring Cloud Gateway配置具体的负载均衡策略?
后端
间彧7 小时前
Spring Cloud Gateway详解与应用实战
后端
EnCi Zheng8 小时前
SpringBoot 配置文件完全指南-从入门到精通
java·spring boot·后端
烙印6018 小时前
Spring容器的心脏:深度解析refresh()方法(上)
java·后端·spring