微服务系列文章之 Nginx反向代理

Nginx反向代理模块的指令是由ngx_http_proxy_module模块进行解析,该模块在安装Nginx的时候已经自己加装到Nginx中了,接下来我们把反向代理中的常用指令一一介绍下:

proxy_pass
proxy_set_header
proxy_redirect

1、proxy_pass

该指令用来设置被代理服务器地址,可以是主机名称、IP地址加端口号形式。

语法 proxy_pass URL;
默认值 ---
位置 location

URL:为要设置的被代理服务器地址,包含传输协议(http,https://)、主机名称或IP地址加端口号、URI等要素。

2、proxy_set_header

该指令可以更改Nginx服务器接收到的客户端请求的请求头信息,然后将新的请求头发送给代理的服务器

语法 proxy_set_header field value;
默认值 proxy_set_header Host $proxy_host; proxy_set_header Connection close;
位置 http、server、location

需要注意的是,如果想要看到结果,必须在被代理的服务器上来获取添加的头信息。

被代理服务器: [192.168.200.146]

server {
        listen  8080;
        server_name localhost;
        default_type text/plain;
        return 200 $http_username;
}

代理服务器: [192.168.200.133]

server {
    listen  8080;
    server_name localhost;

    location /server {
        proxy_pass http://192.168.200.146:8080/;
        proxy_set_header username TOM;
    }
}

访问测试

3、proxy_redirect

该指令是用来重置头信息中的"Location"和"Refresh"的值。

语法 proxy_redirect redirect replacement; proxy_redirect default; proxy_redirect off;
默认值 proxy_redirect default;
位置 http、server、location

》为什么要用该指令?

服务端[192.168.200.146]

server {
    listen  8081;
    server_name localhost;
    if (!-f $request_filename){
      return 302 http://192.168.200.146;
    }
}

代理服务端[192.168.200.133]

server {
  listen  8081;
  server_name localhost;
  location / {
    proxy_pass http://192.168.200.146:8081/;
    proxy_redirect http://192.168.200.146 http://192.168.200.133;
  }
}

》该指令的几组选项

proxy_redirect redirect replacement;

redirect:目标,Location的值
replacement:要替换的值

proxy_redirect default;

default;
将location块的uri变量作为replacement,
将proxy_pass变量作为redirect进行替换

proxy_redirect off;

关闭proxy_redirect的功能
相关推荐
一位卑微的码农3 小时前
深入解析Spring Cloud Config:构建高可用分布式配置中心
分布式·spring cloud·微服务·架构
招风的黑耳4 小时前
使用Nginx本地部署Axure生成的HTML文件,局域网内浏览器通过IP和地址访问
nginx·html·axure·本地部署
s_fox_5 小时前
nginx ngx_http_module(7) 指令详解
运维·nginx·http
若云止水6 小时前
Ubuntu 下 nginx-1.24.0 源码分析 - ngx_process_options
运维·nginx
s_fox_6 小时前
nginx ngx_http_module(9) 指令详解
运维·nginx·http
专注API从业者7 小时前
分布式电商系统中的API网关架构设计
大数据·数据仓库·分布式·架构
uhakadotcom9 小时前
Google DeepMind最近发布了SigLIP 2
人工智能·算法·架构
HsuYang11 小时前
Vite源码学习(十二)——热更新(下)
前端·javascript·架构
BlueBirdssh12 小时前
ARM SOC 架构系统M系、R系、A系
arm开发·架构
m0_7482387813 小时前
Nginx 负载均衡详解
运维·nginx·负载均衡