一、Nginx代理简述

正向代理:客户端<—>代理—>服务端 反向代理: 客户端—>代理<—>服务端

二、Nginx反向代理示例

测试环境:

Proxy 100.100.142.212
Server 100.100.142.213

两台服务器安装Nginx并启动:

  1. yum install nginx -y
  2. systemctl start nginx

1、Server配置服务端

注释掉Nginx自带的配置

  1. [root@server ~]# vim /etc/nginx/nginx.conf

Nginx反向代理 - 图1
编辑Nginx配置文件如下:

  1. [root@server ~]# vim /etc/nginx/conf.d/server.conf
  2. server {
  3. listen 8000;
  4. server_name 100.100.142.213;
  5. location / {
  6. root /opt;
  7. index index.html;
  8. }
  9. }

编写测试HTML文件,并给web目录相对应的权限

  1. [root@server ~]# echo 'test_server' > /opt/index.html && chown -R nginx.nginx /opt

检测Nginx配置文件并重启

  1. [root@server ~]# nginx -t
  2. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  3. nginx: configuration file /etc/nginx/nginx.conf test is successful
  4. [root@server ~]# systemctl restart nginx

访问IP:8000端口即可
Nginx反向代理 - 图2

2、Proxy代理配置

注释掉Nginx自带的配置

  1. [root@proxy ~]# vim /etc/nginx/nginx.conf

Nginx反向代理 - 图3
编辑Nginx配置文件如下:

  1. [root@proxy ~]# vim /etc/nginx/conf.d/proxy.conf
  2. server {
  3. listen 80;
  4. server_name 100.100.142.212;
  5. location / {
  6. proxy_pass http://100.100.142.213:8000;
  7. }
  8. }

检查Nginx配置文件并重启

  1. [root@proxy ~]# nginx -t
  2. nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  3. nginx: configuration file /etc/nginx/nginx.conf test is successful
  4. [root@proxy ~]# systemctl restart nginx

访问代理的IP即可看到的是server端的内容
Nginx反向代理 - 图4