nginx作为web服务器一个重要的功能就是反向代理.nginx反向代理的指令不需要新增额外的模块,默认自带proxy_pass指令,只需要修改配置文件就可以实现反向代理。
而在日常的web网站部署中,经常会用到nginx的proxy_pass反向代理,有一个配置需要弄清楚:配置proxy_pass时,当在后面加的url上了/,相当于是绝对根路径,则nginx不会把位置中匹配的路径部分代理走,如果没有/,则会把匹配的路径部分也给代理走(这样配置可以参考这篇文章)。
centos7系统库中默认是没有nginx的rpm包的,所以我们自己需要先更新下rpm依赖库
1)使用yum安装nginx需要包括nginx的库,安装nginx的库
(root@localhost ~) # rpm -Uvh http://nginx.org/packages/centos/7/noarch/rpms/nginx -释放- centos - 7 - 0. - el7.ngx.noarch.rpm
2)使用下面命令安装nginx
(root@localhost ~) # yum安装nginx
3) nginx配置
# cd/etc/nginx/conf.d/root@localhost ~ [root@localhost conf.d] #猫test.conf 服务器{ 听80; server_name主机; 位置/{ 根/var/www/html; 指数index . html; } } [root@localhost conf.d] #猫/var/www/html/index.html 这是页面的测试! ! ! !
4)启动Nginx
(root@localhost ~) #服务nginx开始//或者使用systemctl开始nginx.service
5)测试访问(103.110.186.23是192.168.1.23机器的外网ip)
[root@localhost conf.d] # curl http://192.168.1.23 这是页面的测试! ! ! !
为了方便测试,先在另一台机器192.168.1.5上部署一个8090端口的nginx,配置如下:
#猫/usr/local/nginx/conf/vhosts/haha.conf root@bastion-IDC ~ 服务器{ 听8090; server_name主机; 位置/{ 根/var/www/html; 指数index . html; } } #猫/var/www/html/index.html root@bastion-IDC ~ 这是192.168.1.5 (root@bastion-IDC ~) #/usr/local/nginx/sbin/nginx - s重载
测试访问(103.110.186.5是192.168.1.5的外网ip):
root@bastion-IDC ~ # curl http://192.168.1.5:8090 这是192.168.1.5
[root@localhost conf.d] #猫test.conf 服务器{ 听80; server_name主机; 位置/{ 根/var/www/html; 指数index . html; } 位置/代理/{ proxy_pass http://192.168.1.5:8090; } }
这样,访问http://192.168.1.23/proxy/就会被代理到http://192.168.1.5:8090每匹配的代理目录不需要存在根目录/var/www/html里面
注意,终端里如果访问http://192.168.1.23/proxy(即后面不带“/?,则会访问失败!因为proxy_pass配置的url后面加了“/?/p>
[root@localhost conf.d] # curl http://192.168.1.23/proxy/这是192.168.1.5 [root@localhost conf.d] # curl http://192.168.1.23/proxy & lt; html> & lt; head> & lt; title> 301搬Permanently & lt;/head> & lt;身体背景=鞍咨痹? & lt; center> & lt; h2> 301搬Permanently & lt;/center> & lt; hr> & lt; center> nginx/1.10.3 & lt;/body> & lt;/html>
页面访问http://103.110.186.23/proxy的时候,会自动加上“/?同理是由于proxy_pass配置的url后面加了“/?,并反代到http://103.110.186.5:8090的结果
2)第二种情况,proxy_pass配置的url后面不加"/"
[root@localhost conf.d] #猫test.conf 服务器{ 听80; server_name主机; 位置/{ 根/var/www/html; 指数index . html; } 位置/代理/{ proxy_pass http://192.168.1.5:8090; } } [root@localhost conf.d] # nginx重启服务 重定向/bin/systemctl重启nginx.servicenginx proxy_pass反向代理配置中url后加不加/的区别介绍