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(用户无感知)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容