PHP Web 端操作 Nginx 配置

PHP Web 端安全操作 Nginx 配置及热重启#

前言#

之前帮客户整了一套基于 GeoIP2 的自动化 AB 站(Nginx Geoip2 处理不同国家 (或城市) 的访问 ),客户最近想通过管理端手动控制 AB 站切换
ar414

不建议使用 system,exec 等执行 shell 命令的函数#

  • 需要复杂的提权操作
  • 一般项目这些函数是被禁止
  • 作为一名合格的 Phper 除非特殊情况,否则是严禁在项目中启用一些涉及到安全性的函数

方案思路#

  1. Nginx vhost 配置文件中 include 片段配置
  2. 后端切换 AB 站时,PHP 逻辑中修改第一步中引入片段配置
  3. Nginx Reload
    • 第一种方案:小型项目使用 crontab 定时执行 nginx -s reload (搭配 worker_shutdown_timeout 使用)
    • 第二种方案(推荐):修改后标记需要 reload 状态 (File or DB or Cache),定时器通过 python 脚本查询是否需要 reload 去执行 nginx -s reload

方案一#

1. 创建片段配置文件#

创建独立片段 Nginx 配置文件,例如 ar414.conf,然后在 nginx vhostinclude

ar414.conf

root /www/wwwroot/ahost;

2. 站点配置文件中 include 配置文件 ar414.conf#

site.conf

server {
        listen       80;
        server_name  0.0.0.0;
        index index.html;
        include /www/wwwroot/abhost/ar414.conf;
    }

3. 后台逻辑中操作 ar414.conf#

if($data['site_set'] == AbHostSiteEnum::Ahost) 
{
    //开启A站
    $ahostPath = AbHostSiteEnum::AhostPath;
    file_put_contents('./ar414.conf',"root {$ahostPath};");
}
else 
{
    //开启B站
    $bhostPath = AbHostSiteEnum::BhostPath;
    file_put_contents('./ar414.conf',"root {$bhostPath};");
}

ar414

4.Nginx 全局配置中设置 worker_shutdown_timeout#

30s 内 Nginx 无法平滑退出,就强行关闭进程

nginx.conf

...
worker_shutdown_timeout  30;

ar414

5. 定时执行 Nginx 热重启#

crontab -e

*/5 * * * * nginx -s reload

Support Author#

coffee alipay wechat

php
本作品采用《CC 协议》,转载必须注明作者和本文链接
AR414
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。