微服务系列文章之 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的功能

猜你喜欢

转载自blog.csdn.net/Coder_Boy_/article/details/131752650