PHP Web 端如何操作 Nginx 配置

来自:互联网
时间:2020-06-18
阅读:

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

前言

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

不建议使用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};");}

4.Nginx全局配置中设置worker_shutdown_timeout

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

nginx.conf

...worker_shutdown_timeout  30;

5.定时执行Nginx热重启

crontab -e

*/5 * * * * nginx -s reload
返回顶部
顶部