反向代理:reverse proxy,指的是代理外网用户的请求到内部的指定的服务器,并将数据返回给用户的一种方式,这是用的比较多的一种方式。
Nginx 除了可以在企业提供高性能的web服务之外,另外还可以将 nginx 本身不具备的请求通过某种预定义的协议转发至其它服务器处理,不同的协议就是Nginx服务器与其他服务器进行通信的一种规范,主要在不同的场景使用以下模块实现不同的功能。
1、nginx服务器配置
1.1、nginx配置文件
安装这里就不演示了,如果不会可以访问一下实现强制https跳转访问自己的域名这篇文章有讲怎么安装,或者看前面写的文章里编译安装nginx,实现多域名https这篇文章也写了。
root@node1:~# cat /apps/nginx/conf/conf.d/test.conf
server {
listen 80;
server_name www.stars.org;
location / {
root /data/nginx/test_web;
index index.html index.htm;
}
}
1.2、准备几个web的目录
root@node1:~# mkdir /data/nginx/{zg,wm,ff}
root@node1:~# echo "`hostname -I` Welcome to zg page" > /data/nginx/test_web/zg/index.html
root@node1:~# echo "`hostname -I` Welcome to wm page" > /data/nginx/test_web/wm/index.html
root@node1:~# echo "`hostname -I` Welcome to ff page" > /data/nginx/test_web/ff/index.html
1.3、验证是否可以访问
2、安装apache服务并编写一个简单页面(测试访问)
root@node2:~# apt -y install apache2 && echo "`hostname -I` Welcome to apache page" > /var/www/html/index.html #这里我使用的是ubuntu系统apt下载的服务会自己开启开机自启动,如果是centos的系统还需要systemctl enable --now httpd启动服务。
root@node3:~# apt -y install apache2 && echo "`hostname -I` Welcome to apache page" > /var/www/html/index.html
3、配置nginx配置文件来实现不同的path代理到不同的Apache服务上
root@node1:~# vim /apps/nginx/conf/conf.d/test.conf
server {
listen 80;
server_name www.stars.org;
root /data/nginx/test_web;
location / {
index index.html index.htm;
}
location /zg {
index index.html index.htm;
proxy_pass http://10.0.0.101:80/; #这里的80端口可以省略不写,下面也是。
}
location /wm {
index index.html index.htm;
proxy_pass http://10.0.0.102:80/;
}
}
root@node1:~# nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
root@node1:~# nginx -s reload
4、测试设置代理的path看一下是否成功代理过去
这个/data/nginx/test_web/目录下的zg和wm都设置了代理,而ff没有设置所以访问ff还是原来的页面。
注意:在使用proxy_pass参数做反向代理时,后端Apache服务器的端口号后面加了/,就相当于alias,它会把访问的路径重新定义到其指定的路径,即访问www.stars.org/zg/或者www.stars.org/wm/的请求直接转发到后端服务器的网站根目录下去寻找主页。如果没有写/,则相当于去后端服务器的网站根目录下的/zg/目录或者/wm/目录下去寻找默认主页。如果我这边取消了配置文件中的/,此时客户端再去访问时就会报404错误,提示无法找到主页。
想要实现反向代理客户端IP透传可以看一下这个文章。