.

一、作用描述

Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行;
其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好;
中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

.
.
.

二、环境示意图

.
.
Nginx 动静分离_第1张图片
.
.
.
.

三、环境描述

.
. .三台CentOS 7.5虚拟机
.
1、代理服务器:
服务:Nginx,并配置代理与动静分离到后端两台动态与静态服务器上
IP:192.168.27.134
.
.
2、静态服务器:
服务:Nginx
IP:192.168.27.133
.
.
3、动态服务器:
服务:nginx、PHP,配置好动态页面并让nginx服务支持动态网页,
IP:192.168.27.132
.
.
.
.

四、配置过程

.
1、三台都要安装Nginx
.
安装epel源
[root@nginx ~]# yum install -y epel-release
安装Nginx
[root@nginx ~]#yum install -y nginx
[root@nginx ~]#rpm -qa nginx
nginx-1.12.2-2.el7.x86_64
.
.
2、防火墙设置
三台服务器都要放行80端口:
[root@nginx ~]#firewall-cmd --zone=public --add-port=80/tcp --permanent
[root@nginx ~]#firewall-cmd --reload
.
.
3、静态服务器
安装lrzsz上传静态文件到服务器测试使用
[root@static ~]#yum install -y lrzsz
[root@static ~]#rz
找到想上传到静态服务器上的图片
.
[root@static ~]#ls
5ab9d79a1ff95.jpg anaconda-ks.cfg
.
[root@static ~]#cp ./5ab9d79a1ff95.jpg /usr/share/nginx/html/
复制到web根目录下
.
.
4、动态服务器
安装PHP
[root@php ~]#yum install php php-fpm -y
.
配置Nginx支持PHP
[root@nginx ~]#rpm -ql nginx
查看文件位置
.
[root@php ~]#vi /etc/nginx/nginx.conf

......
server {
  listen       80;
  server_name  PHPserver;
  root         /usr/share/nginx/html;

  # Load configuration files for the default server block.
  include /etc/nginx/default.d/*.conf;
###<添加的
  location ~ \.php$ {
    root           html;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
  }
###>
  location / {
  }
......

.
.
配置index动态主页
[root@php ~]#vi /usr/share/nginx/html/index.php

.
启动php-fpm
[root@php ~]#systemctl start php-fpm
[root@php ~]#ss -tnl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 127.0.0.1:9000 :
Php-fpm 默认监听在9000端口
.
.
4、Nginx代理服务器
.
修改Nginx配置文件,动静结合
[root@nginx ~]#vi /etc/nginx/nginx.conf

......
# for more information.
    include /etc/nginx/conf.d/*.conf;

###<添加的
    upstream static {
        server    192.168.27.133    max_fails=3 fail_timeout=10s;
        }       
    upstream dynamic {
        server    192.168.27.132    max_fails=3 fail_timeout=10s;
        }

###>

    server {
        listen       80;
        server_name  Nginx;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

###<添加的
        location ~\.(php|jsp)?$ {
                proxy_pass http://dynamic;
                              }
        location ~ .*.(gif|jpg|jpeg|png|bmp|swf|css|js)$ {
                proxy_pass http://static;
                                   }
###>

        location / {
        }
......

.
启动Nginx
[root@nginx ~]#systemctl start nginx
.
.
.
.

五、测试结果

.
.
打开浏览器,输入Nginx服务器的IP地址
.
.
Nginx 动静分离_第2张图片
.
.
.
.
访问先前上传至静态服务器上的图片,还是Nginx服务器的IP
.
.
Nginx 动静分离_第3张图片
.
.
.
.

访问动态服务器上的PHP页
.
.
Nginx 动静分离_第4张图片
.
.
.
.
至此,测试算是完成,但还有许多配置这里没有用到,这只是一个最基础的框架,还得努力完善