四、nginx反向代理

一、反向代理

解释:nginx反向代理如正向代理原理类似,只是实现了不同的功能。客户端将请求发给服务端(代理服务器)后,服务端(代理服务器)并没有自己处理请求,而是交给被代理服务器,由被代理服务器处理完请求,返回给服务端(代理服务器),再通过返回给客户端

结构图如下:
在这里插入图片描述
好处:这样可以隐藏被代理服务器的IP地址(由被代理服务器处理内容,但是用户只能看到服务端(代理服务器)),其是真正处理用户请求的服务器,这样可以一定程度上避免其被攻击

二、实例配置

解释:配置只需配置代理服务器即可,无需配置被代理服务器

参数:

  • proxy_pass:其为被代理服务器地址(示例:proxy_pass http://127.0.0.1$request_url;
  • proxy_set_header:更改Nginx服务器接收到的客户端请求的请求头信息,然后将新的请求头发送给代理的服务器(示例:proxy_set_header name jack;
  • proxy_buffering:是否开启代理服务器的缓冲区(建议:proxy_buffering on;
  • proxy_buffer_size:该指令用来设置从被代理服务器获取的第一部分响应数据的大小(建议:proxy_buffer_size 4 32k;
  • proxy_busy_buffers_size:该指令用来限制同时处于BUSY状态的缓冲总大小(建议:proxy_busy_buffers_size 64k;
  • proxy_temp_file_write_size:用来设置磁盘上缓冲文件的大小(建议:proxy_temp_file_write_size 64k;

1.示例一

server{
    
    
        listen 1235;
        location /{
    
    
        	default_type text/plain;
        	return 200 $arg_url;
        }
}
server {
    
    
        listen 1234;
        location /{
    
    
              proxy_pass http://172.25.52.293:1235/?url=$scheme://$host$request_uri;#用户通过访问端口为1234这个服务,其将请求转发给了端口为1235这台机器,由其处理完之后返回再端口1234的机器,再由端口1234的机器返回给用户
        }
    }

2.示例二

解释:下面的例子相当于访问不同路由,由不同机器进行处理

# 代理服务器
server {
    
    
        listen          1;
        server_name     localhost;
        location /a {
    
    
                proxy_pass http://192.168.xxx.xxx:2/;
        }
        location /b {
    
    
                proxy_pass http://192.168.xxx.xxx:3/;
        }
        location /c {
    
    
                proxy_pass http://192.168.xxx.xxx:4/;
        }
}

# 服务端
server {
    
    
        listen          2;
        default_type text/plain;
        return 200 'port 2'
}
server {
    
    
        listen          3;
        default_type text/plain;
        return 200 'port 3'
}
server {
    
    
        listen          4;
        default_type text/plain;
        return 200 'port 4'
}

猜你喜欢

转载自blog.csdn.net/weixin_46765649/article/details/128053184