您的位置:首页 > 理论基础 > 计算机网络

nginx反代httpd及http-php动静分离

2016-05-25 12:49 411 查看
搭建网络:
后端RS1服务器内网:192.168.1.3
前端A服务器:
外网:172.18.11.111
内网:192.168.1.2
RS1启动httpd并提供页面:
]# systemctl start httpd.serivce]# vim /var/www/html/index.htmlRS1-192.168.1.3

在A主机安装nginx
]# rpm -ivh nginx-1.8.0-1.el7.ngx.x86_64.rpm]# rpm -ql nginx ]# vim /etc/nginx/nginx.conf<hr />   其中:include /etc/nginx/conf.d/*.conf;       【表示每个*.conf定义了一个服务器】  只需在/etc/nginx/conf.d/default.conf配置即可: ]# cp /etc/nginx/conf.d/default.conf{,.bak} ]# vim /etc/nginx/conf.d/default.conf<hr />   只需添加代理:location / {  #root /usr/share/nginx/html;  proxy_pass http://192.168.1.3;  index index.html index.htm;}   在浏览器访问:http://172.18.11.111  显示:RS1-192.168.1.3  表明已经把请求代理到后端的RS1上了;    在RS1上创建一bbs的页面:]# mkdir /var/www/html/bbs]# vim /var/www/html/bbs/index.html<hr /> BBS   在浏览器访问:http://172.18.11.111/bbs/  显示:BBS  表示直接映射到后端;其实,也可以只映射某一个url;  在编辑location有url:]# vim /etc/nginx/conf.d/default.conf<hr /> location / {  root /usr/share/nginx/html;  index index.html index.htm;} location /bbs/ {  proxy_pass http://192.168.1.3;}   在浏览器访问:http://172.18.11.111  显示:nginx提供的欢迎页;  如果在浏览器访问:http://172.18.11.111/bbs  显示:BBS   编辑]# vim /etc/nginx/conf.d/default.conf<hr /> location /bbs/ {  proxy_pass http://192.168.1.3/;}   如果在浏览器访问:http://172.18.11.111/bbs  显示:RS1-172.18.11.8  完成路径映射;   编辑]# vim /etc/nginx/conf.d/default.conf<hr /> location ~* \.(jpg|gif|png)$ {  proxy_pass http://192.168.1.3;}

把jpg等结尾的资源都传到后端;
如果在浏览器访问:http://172.18.11.111/1.jpg
显示:图片在RS1的/var/www/html/1.jpg如果定义php结尾的动态资源传给后端主机,其它资源发往另一主机,如果能匹配动静的资源就可实现动静分离;

注意:location中定义的url,还proxy_pass中定义的url的区别;

下面演示动静分离:

再开启一台RS2主机,可以只接把它配置成php-fpm,前端nginx代理时,就可使用fastcgi;
也可配置成http+php,前端nginx可通过基于http协议向后端代理;
以http+php,前端nginx可通过基于http向后端代理为模型演示;

RS2:192.168.1.4
安装http+php]# yum -y install php httpd并提供php测试页:]# vim /var/www/html/index.php----------------------------------------------------------<h1>RS2-192.168.1.4</h1>phpinfo();?>
在前端DR1代理上配置:
只把php发给RS2]# vim /etc/nginx/conf.d/default.conf--------------------------------------------------------------------------------------location / {    # root /usr/share/nginx/html;    proxy_pass http://192.168.1.3;    index index.html index.htm;} location ~* \.php$ {    proxy_pass http://192.168.1.4;}
开启RS1和RS2的httpd服务;
在浏览器访问:http://172.18.11.111/
显示:RS1-172.18.11.8在浏览器访问:http://172.18.11.111/1.jpg
显示:显示图片在浏览器访问:http://172.18.11.111/index.php
显示:RS2-192.168.1.4和php的测试页;以上实现了nginx当做代理服务器,把http的静态资源和php的动态资源分离转发给后端不同的主机;
在做实际实验时,把php安装一个phpmyadmin有可能无法完成显示正常,因为有些静态页面是在动态页面基础上生成的;需要在前端服务器进行url重写;

本文出自 “王强的博客” 博客,请务必保留此出处http://wqiang.blog.51cto.com/6074114/1782966
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: