PHP Web 端操作 Nginx 配置

PHPNginx发布于2020-07-05 / 更新于2021-01-02 07:04

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};");
}

4.Nginx全局配置中设置worker_shutdown_timeout

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

nginx.conf

...
worker_shutdown_timeout  30;

5.定时执行Nginx热重启

crontab -e

*/5 * * * * nginx -s reload
I am a full-stack independent development engineer from China. I love to participate in open source and focus on developing the Web, iOS App & Android App (React Native), desktop applications (Eletron), crawlers, back-end services, system architecture

讨论

1
123123123
123
12312312
123
1231231212
1432
23423
anonymous
234234234
anonymous
4234234 sdf
anonymous
沙发
anonymous
安抚sgf
anonymous
安抚
anonymous
阿斯蒂芬
anonymous
好!

目录

1.PHP Web端安全操作Nginx配置及热重启
1.1前言
1.2不建议使用system,exec等执行shell命令的函数
1.3方案思路
2.方案一
2.11.创建片段配置文件
2.22.站点配置文件中include配置文件ar414.conf
2.33.后台逻辑中操作ar414.conf
2.44.Nginx全局配置中设置workershutdowntimeout
2.55.定时执行Nginx热重启