当前位置: 首页 > 编程文章 >

Nginx实现动静分离的完整部署方案

Nginx实现动静分离的完整部署方案

作者:周言时间:2025-05-29 11:10:59浏览:939

本文介绍基于Redhat8和CentOS7环境的Nginx动静分离部署方法。通过在三台主机上分别配置Nginx反向代理、LNMP动态服务集群以及HTTPD静态资源服务器,实现请求的智能分发。关闭防火墙并配置SELinux后,利用Nginx的location规则将PHP请求转发至后端LNMP节点,静态文件由HTTPD节点处理,从而提升系统性能与扩展性。

本文目录展开

本示例详细讲解如何利用Nginx构建动静分离架构,具备实际参考价值。具体实施步骤如下所述。

环境准备:

系统/主机名 IP地址 服务
Redhat8 :server1 192.168.244.131 nginx
Redhat8:server2 192.168.244.133 lnmp
Content7:node3 192.168.244.142 httpd

需确保三台主机均停止防火墙服务并禁用开机自启,同时修改SELinux配置文件为disabled状态以保障网络通信顺畅。


[root@server1 ~]# systemctl stop firewalld
[root@server1 ~]# systemctl disable firewalld
[root@server1 ~]# vim /etc/selinux/config 
SELINUX=disabled

在server1上部署nginx


[root@server1 opt]# cat nginx.sh 
#!/bin/bash

if [ $UID -ne 0 ];then
        echo "Please use administrator account"
        exit
fi

app_a=nginx-1.20.1.tar.gz

dir_a=/usr/local
dir_b=/var/log
dir_c=nginx-1.20.1

if [ ! -d $dir_b/nginx ];then
        mkdir -p $dir_b/nginx
fi
chown -R nginx.nginx $dir_b/nginx

yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++  make
yum -y groups mark install 'Development Tools'

id nginx &>/dev/null 
if [ $? -ne 0 ];then
        useradd -r -M -s /sbin/nologin nginx
fi

tar xf bag/$app_a -C $dir_a

cd  $dir_a/$dir_c
if [ ! -d $dir_a/nginx ];then
        ./configure \
                --prefix=$dir_a/nginx \
                --user=nginx \
                --group=nginx \
                --with-debug \
                --with-http_ssl_module \
                --with-http_realip_module \
                --with-http_image_filter_module \
                --with-http_gunzip_module \
                --with-http_gzip_static_module \
                --with-http_stub_status_module \
                --http-log-path=$dir_b/nginx/access.log \
                --error-log-path=$dir_b/nginx/error.log  && make  && make install
fi

cd ..
if [ ! -f /etc/profile.d/nginx.sh  ];then
        echo "export PATH=$dir_a/nginx/sbin:\$PATH" > /etc/profile.d/nginx.sh
fi

cat > /usr/lib/systemd/system/nginx.service << EOF
[Unit]
Description=Nginx server daemon
Wants=sshd-keygen.target

[Service]
Type=forking
ExecStart=$dir_a/nginx/sbin/nginx
ExecStop=$dir_a/nginx/sbin/nginx -s stop
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target
EOF


systemctl daemon-reload
systemctl enable --now nginx

检查端口监听状态


[root@server1 ~]# ss -antl
State    Recv-Q   Send-Q       Local Address:Port                     Peer Address:Port                 
LISTEN   0        128                0.0.0.0:22                            0.0.0.0:*                    
LISTEN   0        128                0.0.0.0:80                            0.0.0.0:*                    
LISTEN   0        128                   [::]:22                               [::]:*   

验证页面访问是否正常

在这里插入图片描述

在server上部署lnmp

首先安装Nginx组件


[root@server2 lnmp]# cat install.sh 
#!/bin/bash

if [ $UID -ne 0 ];then
        echo "Please use administrator account"
        exit
fi

app_a=nginx-1.20.1.tar.gz

dir_a=/usr/local
dir_b=/var/log
dir_c=nginx-1.20.1

if [ ! -d $dir_b/nginx ];then
        mkdir -p $dir_b/nginx
fi
chown -R nginx.nginx $dir_b/nginx

yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++  make
yum -y groups mark install 'Development Tools'

id nginx &>/dev/null 
if [ $? -ne 0 ];then
        useradd -r -M -s /sbin/nologin nginx
fi

tar xf bag/$app_a -C $dir_a

cd  $dir_a/$dir_c
if [ ! -d $dir_a/nginx ];then
        ./configure \
                --prefix=$dir_a/nginx \
                --user=nginx \
                --group=nginx \
                --with-debug \
                --with-http_ssl_module \
                --with-http_realip_module \
                --with-http_image_filter_module \
                --with-http_gunzip_module \
                --with-http_gzip_static_module \
                --with-http_stub_status_module \
                --http-log-path=$dir_b/nginx/access.log \
                --error-log-path=$dir_b/nginx/error.log  && make  && make install
fi

cd ..
if [ ! -f /etc/profile.d/nginx.sh  ];then
        echo "export PATH=$dir_a/nginx/sbin:\$PATH" > /etc/profile.d/nginx.sh
fi

cat > /usr/lib/systemd/system/nginx.service << EOF
[Unit]
Description=Nginx server daemon
Wants=sshd-keygen.target

[Service]
Type=forking
ExecStart=$dir_a/nginx/sbin/nginx
ExecStop=$dir_a/nginx/sbin/nginx -s stop
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now nginx

接着配置MySQL数据库服务


[root@server2 lnmp]# cat mysql.sh 
#!/bin/bash

if [ $UID -ne 0 ];then
        echo "root?"
        exit
fi

dir_a=/usr/local
dir_b=/opt/data
app_a=mysql-5.7.34-linux-glibc2.12-x86_64.tar.gz
app_b=mysql-5.7.34-linux-glibc2.12-x86_64

id mysql  &>/dev/null
if [ $? -ne 0 ];then
        useradd -r -M -s /sbin/nologin mysql
 fi


yum -y install ncurses-compat-libs ncurses-devel openssl-devel openssl cmake mariadb-devel 


if [ ! -d $dir_a/$app_b ];then
        tar xf bag/$app_a -C $dir_a
fi

if [ ! -d $dir_a/mysql ];then
        ln -sv $dir_a/$app_b  $dir_a/mysql
fi
chown -R mysql:mysql $dir_a/mysql*

echo "export PATH=$dir_a/mysql/bin:\$PATH" > /etc/profile.d/mysql.sh

source /etc/profile.d/mysql.sh

if [ ! -d /$dir_b ];then
        mkdir -p /$dir_b 
        chown -R mysql.mysql /$dir_b
fi


content=$(ls $dir_b | wc -l)
if [ $content -eq 0  ];then
        mysqld --initialize-insecure --user mysql --datadir $dir_b
fi

cat > /etc/my.cnf < /usr/lib/systemd/system/mysqld.service <

随后编译安装PHP解析器


 https://www.php.net/distributions/php-8.0.10.tar.xz

解压安装包


[root@server2 ~]# tar -xf  php-8.0.10.tar.gz  -C /usr/local/

安装必要的依赖包


[root@server2 ~]# wget http://mirrors.aliyun.com/repo/epel-7.repo
[root@server1 ~]# yum -y install libxml2 libxml2-devel openssl openssl-devel bzip2 bzip2-devel libcurl libcurl-devel libicu-devel libjpeg libjpeg-devel libpng libpng-devel openldap-devel  pcre-devel freetype freetype-devel gmp gmp-devel libmcrypt libmcrypt-devel readline readline-devel libxslt libxslt-devel mhash mhash-devel  php-mysqlnd  libsqlite3x-devel libzip-devel
[root@server2 ~]# yum -y install http://mirror.centos.org/centos/8-stream/PowerTools/x86_64/os/Packages/oniguruma-devel-6.8.2-2.el8.x86_64.rpm

执行编译安装流程


[root@server2 ~]# cd /usr/local/php-8.0.10/
[root@server2 php-8.0.10]# ./configure --prefix=/usr/local/php8  --with-config-file-path=/etc --enable-fpm --disable-debug --disable-rpath --enable-shared --enable-soap --with-openssl --enable-bcmath --with-iconv --with-bz2 --enable-calendar --with-curl --enable-exif  --enable-ftp --enable-gd --with-jpeg --with-zlib-dir --with-freetype --with-gettext --enable-mbstring --enable-pdo --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-readline --enable-shmop --enable-simplexml --enable-sockets --with-zip --enable-mysqlnd-compression-support --with-pear --enable-pcntl --enable-posix
......
......
......
config.status: creating ext/phar/phar.phar.1
config.status: creating main/php_config.h
config.status: executing default commands

+--------------------------------------------------------------------+
| License:                                                           |
| This software is subject to the PHP License, available in this     |
| distribution in the file LICENSE. By continuing this installation  |
| process, you are bound by the terms of this license agreement.     |
| If you do not agree with the terms of this license, you must abort |
| the installation process at this point.                            |
+--------------------------------------------------------------------+

Thank you for using PHP.


[root@server2 php-8.0.10]# make
.......
.......
.......
invertedregexiterator.inc
pharcommand.inc
phar.inc

Build complete.
Don't forget to run 'make test'.

[root@server2 php-8.0.10]# make install
......
......
/root/php-8.0.10/build/shtool install -c ext/phar/phar.phar /usr/local/php8/bin/phar.phar
ln -s -f phar.phar /usr/local/php8/bin/phar
Installing PDO headers:           /usr/local/php8/include/php/ext/pdo/

调整php-fpm参数配置


[root@server2 php-8.0.10]# cp /etc/php.ini /opt/
[root@server2 php-8.0.10]# cp php.ini-production /etc/php.ini 
cp: overwrite '/etc/php.ini'? y
[root@server2 php-8.0.10]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@server2 php-8.0.10]# chmod +x /etc/init.d/php-fpm
[root@server2 php-8.0.10]# cd  ..
[root@server2 local]# cd  php8/
[root@server2 php8]# cd  etc/
[root@server2 etc]# cp php-fpm.conf.default php-fpm.conf
[root@server2 etc]# cp php-fpm.d/www.conf.default php-fpm.d/www.conf
[root@server2 etc]# cd  php-fpm.d
[root@server2 php-fpm.d]# ls
www.conf  www.conf.default

设置环境变量路径


[root@server2 ~]#  echo 'export PATH=/usr/local/php8/bin:$PATH' > /etc/profile.d/php.sh
[root@server2 ~]# cat /etc/profile.d/php.sh
export PATH=/usr/local/php8/bin:$PATH
[root@server2 ~]# source /etc/profile.d/php.sh
[root@server2 ~]# which php
/usr/local/php8/bin/php

创建systemd服务单元文件


[root@server2 ~]# cat /usr/lib/systemd/system/php-fpm.service 
[Unit]
Description=php-fpm server daemon
After=network.target 

[Service]
Type=forking

ExecStart=/etc/init.d/php-fpm start
ExecStop=/etc/init.d/php-fpm stop
ExecReload=/bin/kill -HUP $MAINPID

[Install]
[root@server2 ]# systemctl  daemon-reload

启动PHP-FPM进程


[root@server2 ~]# systemctl start php-fpm
[root@server2 ~]# ss -antl
State    Recv-Q   Send-Q       Local Address:Port                     Peer Address:Port                 
LISTEN   0        128              127.0.0.1:9000                          0.0.0.0:*                    
LISTEN   0        128                0.0.0.0:80                            0.0.0.0:*                    
LISTEN   0        128                0.0.0.0:22                            0.0.0.0:*                    
LISTEN   0        80                       *:3306                                *:*                    
LISTEN   0        128                   [::]:22                               [::]:*  

在nginx.conf中定义虚拟主机规则


[root@server2 ~]# cd  /usr/local/nginx/html/
[root@server2 html]# ls
50x.html  index.html
[root@server2 html]# vim index.php
[root@server2 html]# cat index.php 
<?php
    phpinfo();
?>
[root@server2 conf]# pwd /usr/local/nginx/conf [root@server2 conf]# vim nginx.conf ........ http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log logs/access.log main; sendfile on; ...... location / { root html; index index.php index.html index.htm; } ..... 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; } [root@server2 conf]# nginx -s reload

测试访问连通性

在这里插入图片描述

node3部署httpd


[root@node3 ~]# yum -y install httpd

启动Apache服务


[root@node3 ~]# systemctl start httpd
[root@node3 ~]# ss -antl
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN     0      128     *:22                  *:*                  
LISTEN     0      100    127.0.0.1:25                  *:*                  
LISTEN     0      128    :::80                 :::*                  
LISTEN     0      128    :::22                 :::*                  
LISTEN     0      100       ::1:25                 :::*                 

确认静态页面可访问

在这里插入图片描述

实现分离部署

修改server1上的nginx.conf配置文件


[root@server1 ~]# cat /usr/local/nginx/conf/nginx.conf

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    upstream cm {                #静态资源地址
        server 192.168.244.142;
    }
    
    upstream nm {                #动态资源地址
        server 192.168.244.133;
    }


    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://cm;     #指向静态
        }
        
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        location ~ \.php$ {         #指向动态
            proxy_pass   http://nm;
        }

[root@server1 ~]# nginx -s reload

浏览器访问 192.168.244.131

在这里插入图片描述

访问 192.168.244.131/index.php

在这里插入图片描述

至此,关于Nginx实现动静分离的方法示例已介绍完毕。如需了解更多Nginx动静分离相关内容,欢迎查阅本站过往文章或继续浏览后续推荐内容,感谢大家的支持!

上一篇
Linux下安装Nginx及配置管理指南

本文介绍在 Linux 环境下安装 Nginx 的完整流程,包括 gcc、pcre-devel 等依赖库的安装,源码编译步骤,以及启动、停止和重启命令。同时涵盖修改默认 80 端口为其他端口(如 8090)的方法,配置文件语法检查技巧,以及解决端口占用和阿里云安全组拦截等常见问题的排查思路。

下一篇
基于Lua模块实现Nginx防盗链配置详解

本文介绍利用Nginx的Lua模块(lua_nginx_module)替代传统accesskey模块实现下载服务器的防盗链功能。核心原理是通过生成包含加密签名的动态链接,并在接收端验证签名有效性来阻止非法盗链。配置过程需开启SSI以获取自定义变量,并通过set_by_lua指令计算MD5哈希值进行身份校验。

相关文章

更多
CentOS LNMP 服务器部署标准指南

本文介绍在 CentOS 系统上从零开始部署 LNMP(Linux, Nginx, MySQL, PHP)环境的完整流程。内容涵盖系统初始化、依赖包安装、Nginx 编译配置、PHP-FPM 集成及 Memcached 扩展安装,旨在为新手提供一份可操作的标准化部署方案。

2025.03.26 928
LNMP环境下phpinfo无法显示的排查与修复

本文详细记录了在CentOS 7 LNMP环境中遇到phpinfo页面无法显示的问题排查过程。通过验证Nginx与PHP-FPM服务状态,重点分析了Nginx主机配置中关于index.php默认首页及fastcgi_pass参数设置,并检查了PHP-FPM监听端口配置。最终通过修正配置并重启服务成功解决该问题,为类似环境提供参考。

2025.08.29 876
Nginx路径转发配置详解:反向代理、负载均衡与动静分离

本文详解Nginx如何配置根据路径进行请求转发,涵盖反向代理、负载均衡及动静分离的核心实现。通过配置proxy_pass指令结合upstream模块,可实现将客户端请求分发至不同后端服务器或端口。文中还介绍了轮询、权重、IP绑定等负载均衡策略,以及利用location块区分静态资源与动态请求的处理逻辑,帮助优化服务器负载并提升访问速度。

2025.08.03 837
Debian系统手动配置LNMP环境教程

本文介绍在Debian系统中通过apt-get手动安装并配置Nginx、MySQL和PHP(phpMyAdmin)的完整流程。涵盖数据库安全设置、PHP扩展与Memcached安装、Nginx FastCGI参数调整及站点伪静态规则配置,适用于需要自定义生产环境的VPS用户。

2025.01.24 818
基于Docker镜像快速搭建LNMP环境完整指南

本文详细介绍如何使用官方脚本安装Docker,并基于2233466866/lnmp镜像快速构建LNMP开发环境。内容涵盖容器创建、目录挂载、MySQL密码重置、PHP时区设置以及Nginx多站点配置文件编写,帮助开发者高效部署Web服务。

2026.07.30 762
CentOS 7.2 搭建 LNMP (Nginx+MySQL+PHP) 环境完整教程

本文介绍在阿里云 ECS CentOS 7.2 系统下搭建 LNMP 环境的步骤。通过配置 Yum 仓库安装 Nginx、MySQL 5.6 及 PHP 7.0,并启用 PHP-FPM 管理 FastCGI 进程。文中详细说明了各服务的配置文件修改、权限设置、开机自启配置以及 phpMyAdmin 的安装与登录故障排除方法。

2025.04.16 667

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。