其他话不多说,下面来学习一下 Nginx 的反向代理。需要有 Linux 和 Nginx 环境。
什么是反向代理
反向代理: 看下面原理图,就一目了然。其实客户端对代理是无感知的,因为客户端不需要任何配置就可以访问,我们只需要将请求发送到反向代理服务器,由反向代理服务器去选择目标服务器获取数据后,在返回给客户端,此时反向代理服务器和目标服务器对外就是一个服务器,暴露的是代理服务器地址,隐藏了真实服务器 IP 地址。
正向代理: 如果把局域网外的 Internet 想象成一个巨大的资源库,则局域网中的客户端要访问 Internet,则需要通过代理服务器来访问,这种代理服务就称为正向代理。
装包
rpm -ivh epel-release-latest-7.noarch.rpm
yum install nginx -y
修改配置
在测试机本地上监听8080、8081、8082三个端口,模拟三台主机分别处理来自客户端访问picture、video、text的请求
[root@node9 ~]# vim /etc/nginx/nginx.conf
server {
listen 80;
server_name 192.168.2.19;
access_log /usr/local/nginx/test/data/logs/www.test151.com.log;
error_log /usr/local/nginx/test/data/logs/www.test151.com.error.log;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location ~ /picture/ {
proxy_pass http://127.0.0.1:8080;
}
location ~ /video/ {
proxy_pass http://127.0.0.1:8081;
}
location ~ /text/ {
proxy_pass http://127.0.0.1:8082;
}
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
补充:location 指令说明
该指令用于匹配 URL, 语法如下:
location [ = | ~ | ~* | ^~] uri {
}
=
:用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配, 如果匹配成功,就停止继续向下搜索并立即处理该请求。~
:用于表示 uri 包含正则表达式,并且区分大小写。~*
:用于表示 uri 包含正则表达式,并且不区分大小写。^~
:用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求
字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location块中的正则 uri 和请求字符串做匹配。
注意:如果 uri 包含正则表达式,则必须要有 ~ 或者 ~* 标识
创建如下目录结构,并在index.html中分别添加picture、video、text文本信息
[root@node9 tmp]# mkdir -p {8080/picture,8081/videx,8082/text}
[root@node9 tmp]# tree .
.
├── 8080
│ └── picture
│ └── index.html
├── 8081
│ └── video
│ └── index.html
└── 8082
└── text
└── index.html
6 directories, 3 files
[root@node9 tmp]#
进入8080目录运行
python -m SimpleHTTPServer 8080
进入8081目录运行
python -m SimpleHTTPServer 8081
进入8082目录运行
python -m SimpleHTTPServer 8082
测试
[zyq@zyq ~]$ curl 192.168.2.19:/picture/index.html
picture
[zyq@zyq ~]$ curl 192.168.2.19:/video/index.html
video
[zyq@zyq ~]$ curl 192.168.2.19:/text/index.html
text
[zyq@zyq ~]$