PHP Web端安全操作Nginx配置及熱重啟
前言
之前幫客戶整了一套基于GeoIP2的自動(dòng)化AB站(Nginx Geoip2 處理不同國家 (或城市) 的訪問 ),客戶最近想通過管理端手動(dòng)控制AB站切換
不建議使用system,exec等執(zhí)行shell命令的函數(shù)
- 需要復(fù)雜的提權(quán)操作
- 一般項(xiàng)目這些函數(shù)是被禁止
- 作為一名合格的Phper除非特殊情況,否則是嚴(yán)禁在項(xiàng)目中啟用一些涉及到安全性的函數(shù)
方案思路
- Nginx vhost配置文件中
include
片段配置 - 后端切換AB站時(shí),PHP邏輯中修改第一步中引入片段配置
- Nginx Reload
- 第一種方案:小型項(xiàng)目使用crontab定時(shí)執(zhí)行nginx -s reload(搭配worker_shutdown_timeout使用)
- 第二種方案(推薦):修改后標(biāo)記需要reload狀態(tài)(File or DB or Cache),定時(shí)器通過python腳本查詢是否需要reload去執(zhí)行nginx -s reload
方案一
1.創(chuàng)建片段配置文件
創(chuàng)建獨(dú)立片段Nginx配置文件,例如ar414.conf
,然后在nginx vhost
中include
ar414.conf
root /www/wwwroot/ahost;
2.站點(diǎn)配置文件中include
配置文件ar414.conf
site.conf
server { listen 80; server_name 0.0.0.0; index index.html; include /www/wwwroot/abhost/ar414.conf; }
3.后臺(tái)邏輯中操作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全局配置中設(shè)置worker_shutdown_timeout
30s內(nèi)Nginx無法平滑退出,就強(qiáng)行關(guān)閉進(jìn)程
nginx.conf
...worker_shutdown_timeout 30;
5.定時(shí)執(zhí)行Nginx熱重啟
crontab -e
*/5 * * * * nginx -s reload
推薦教程:《PHP》