#!/bin/bash # 定义Nginx配置文件目录 NGINX_CONF_DIR="/www/server/panel/vhost/nginx" # 检查目录是否存在 if [ ! -d "$NGINX_CONF_DIR" ]; then echo "错误:Nginx配置目录 $NGINX_CONF_DIR 不存在!" exit 1 fi echo "===== 开始处理 Nginx 配置文件 =====" echo "目标目录:$NGINX_CONF_DIR" echo "匹配规则:所有以 www 开头的 .conf 文件" echo "处理内容:1.删除error_page 404/502配置行 2.配置php访问规则" echo "====================================" # 遍历所有www开头的conf文件 for conf_file in "${NGINX_CONF_DIR}"/www*.conf; do # 检查文件是否存在(防止无匹配文件时出错) [ -e "$conf_file" ] || continue echo -e "\n正在处理文件:$conf_file" # 新增:删除包含error_page 404 /404.html; 和 error_page 502 /502.html; 的行 sed -i '/error_page 404 \/404.html;/d' "$conf_file" sed -i '/error_page 502 \/502.html;/d' "$conf_file" echo " → 已清理404/502错误页配置行" # 检查文件中是否已存在目标location规则 if grep -q "location ~ ^/index.php" "$conf_file"; then echo " → 已存在php访问规则,跳过" continue fi # 执行php规则替换 sed -i 's/include enable-php-72.conf;/location ~ ^\/index.php{\n include enable-php-72.conf;\n}\nlocation ~* \\.(php){\n deny all;\n}/g' "$conf_file" if [ $? -eq 0 ]; then echo " → php访问规则替换成功!" else echo " → php访问规则替换失败!" fi done echo -e "\n===== 配置替换&清理完成 =====" # ====================== # 自动重载 Nginx # ====================== echo -e "\n正在重载 Nginx 配置..." /www/server/nginx/sbin/nginx -s reload if [ $? -eq 0 ]; then echo "✅ Nginx 重载成功!" else echo "❌ Nginx 重载失败,请检查配置是否有误!" exit 1 fi echo -e "\n🎉 全部任务完成!"