#需要注意的是
代理proxy_pass http://192.168.29.188:5000; 我这里使用的是容器中的flask地址
#!/bin/bash# 1. 查看当前系统 nginx 配置文件位置
nginxconf_path=$(whereis nginx | awk '{print $2}')/conf/nginx.conf
echo "nginxconf_path: $nginxconf_path"# 2. 查看主配置文件是否有导入扩展配置文件的指令
if grep -q "include /usr/local/nginx/conf/conf.d/*.conf;" $nginxconf_path; thenecho "Import extended configuration: /usr/local/nginx/conf/conf.d/*.conf"
elseecho "No import extended configuration"# 2.1. 若没有,则需要在主配置文件中添加 include /usr/local/nginx/conf/conf.d/*.conf;sudo sed -i '/http {/a include /usr/local/nginx/conf/conf.d/*.conf;' $nginxconf_pathecho "Added import extended configuration: /usr/local/nginx/conf/conf.d/*.conf"
fi# 3. 查看扩展配置文件目录是否存在
if [ -d "/usr/local/nginx/conf/conf.d" ]; thenecho "Extended configuration directory exists"
elseecho "Extended configuration directory does not exist"# 3.1. 若不存在,则需要创建扩展配置文件目录sudo mkdir -p /usr/local/nginx/conf/conf.decho "Created extended configuration directory"
fi# 4. 定义配置文件名数组
conf_files=("domain.conf" "ip.conf" "port.conf")# 5. 检查并创建配置文件
for file in "${conf_files[@]}"; doif [ -f "/usr/local/nginx/conf/conf.d/$file" ]; thenecho "Extended configuration file exists: $file"elseecho "Extended configuration file does not exist: $file"# 5.1. 若不存在,则需要创建扩展配置文件echo "Creating extended configuration file: $file"sudo touch "/usr/local/nginx/conf/conf.d/$file"fi
done# 6. 定义函数来写入配置文件
write_config() {local file_path=$1local server_name=$2local listen_port=$3cat <<EOF | sudo tee "$file_path" > /dev/null
server {listen $listen_port;server_name $server_name;location / {# 代理转发到我的docker中的flask项目proxy_pass http://192.168.29.188:5000;}
}
EOF
}# 7. 交互式选择配置
echo "Select virtual host configuration type:"
select conf_type in "IP" "Domain" "Port" "Quit"; doecho "You selected: $conf_type" # 调试输出case "$conf_type" in"Domain") write_config "/usr/local/nginx/conf/conf.d/${conf_files[0]}" "example.com" 80break;;"IP") write_config "/usr/local/nginx/conf/conf.d/${conf_files[1]}" "192.168.29.129" 80break;;"Port") write_config "/usr/local/nginx/conf/conf.d/${conf_files[2]}" "example.com" 9888break;;"Quit") exit 0;;*) echo "Invalid input. Please try again.";;esac
done# 8. 重启 nginx 服务并检查是否成功
if sudo systemctl restart nginx; thenecho "Nginx service restarted successfully"
elseecho "Failed to restart Nginx service"exit 1
fi