本文目录导读:

我来为您提供一个自动配置Nginx反向代理的Python脚本,支持多种配置方式。
基础交互式脚本
#!/usr/bin/env python3
"""
Nginx反向代理自动配置脚本
支持添加、查看、删除反向代理配置
"""
import os
import sys
import json
import subprocess
from pathlib import Path
class NginxReverseProxyManager:
def __init__(self):
self.nginx_available = "/etc/nginx/sites-available"
self.nginx_enabled = "/etc/nginx/sites-enabled"
self.nginx_conf = "/etc/nginx/nginx.conf"
self.config_dir = "/etc/nginx/conf.d"
def check_nginx(self):
"""检查Nginx是否安装"""
try:
subprocess.run(["nginx", "-v"], capture_output=True)
return True
except FileNotFoundError:
print("❌ Nginx未安装,请先安装Nginx")
return False
def test_nginx_config(self):
"""测试Nginx配置"""
result = subprocess.run(["nginx", "-t"], capture_output=True, text=True)
return result.returncode == 0
def reload_nginx(self):
"""重新加载Nginx"""
try:
subprocess.run(["nginx", "-s", "reload"], check=True)
return True
except subprocess.CalledProcessError:
return False
def create_proxy_config(self, server_name, proxy_pass, port=80,
ssl=False, cert_path="", key_path=""):
"""
创建反向代理配置
Args:
server_name: 域名或IP
proxy_pass: 后端服务地址 (如 http://127.0.0.1:8080)
port: 监听端口
ssl: 是否启用SSL
cert_path: SSL证书路径
key_path: SSL密钥路径
"""
config = f"""
# 反向代理配置 - {server_name}
server {{
listen {port};
server_name {server_name};
# 日志配置
access_log /var/log/nginx/{server_name}_access.log;
error_log /var/log/nginx/{server_name}_error.log;
# 反向代理配置
location / {{
proxy_pass {proxy_pass};
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket支持
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 超时配置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {{
expires 7d;
add_header Cache-Control "public, no-transform";
}}
}}
"""
# SSL配置
if ssl and cert_path and key_path:
config = f"""
# 反向代理配置 - {server_name} (HTTPS)
server {{
listen {port} ssl http2;
server_name {server_name};
ssl_certificate {cert_path};
ssl_certificate_key {key_path};
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# SSL会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# 日志配置
access_log /var/log/nginx/{server_name}_access.log;
error_log /var/log/nginx/{server_name}_error.log;
# 反向代理配置
location / {{
proxy_pass {proxy_pass};
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket支持
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 超时配置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}}
# 强制HTTPS重定向
error_page 497 https://$host$request_uri;
}}
# HTTP重定向到HTTPS
server {{
listen 80;
server_name {server_name};
return 301 https://$server_name$request_uri;
}}
"""
return config
def add_proxy(self, server_name, proxy_pass, port=80, ssl=False):
"""添加反向代理配置"""
filename = f"{server_name}.conf"
filepath = os.path.join(self.nginx_available, filename)
# 生成配置
config = self.create_proxy_config(server_name, proxy_pass, port, ssl)
# 保存配置文件
try:
with open(filepath, 'w') as f:
f.write(config)
print(f"✅ 配置文件已创建: {filepath}")
except PermissionError:
print("❌ 权限不足,请使用sudo运行")
return False
# 创建软链接
link_path = os.path.join(self.nginx_enabled, filename)
if not os.path.exists(link_path):
os.symlink(filepath, link_path)
print(f"🔗 已启用配置: {link_path}")
# 测试并重载配置
print("\n🔄 正在测试Nginx配置...")
if self.test_nginx_config():
print("✅ 配置测试通过")
if self.reload_nginx():
print("✅ Nginx已重新加载")
else:
print("❌ Nginx重载失败")
else:
print("❌ 配置测试失败,请检查配置")
return False
return True
def remove_proxy(self, server_name):
"""删除反向代理配置"""
filename = f"{server_name}.conf"
available_path = os.path.join(self.nginx_available, filename)
enabled_path = os.path.join(self.nginx_enabled, filename)
# 删除软链接
if os.path.exists(enabled_path):
os.remove(enabled_path)
print(f"🗑️ 已禁用配置: {enabled_path}")
# 删除配置文件
if os.path.exists(available_path):
os.remove(available_path)
print(f"🗑️ 已删除配置文件: {available_path}")
# 重载Nginx
if self.test_nginx_config():
self.reload_nginx()
print("✅ Nginx已重新加载")
else:
print("❌ 配置测试失败")
def list_proxies(self):
"""列出所有反向代理配置"""
print("\n📋 当前反向代理配置:")
print("-" * 60)
if not os.path.exists(self.nginx_enabled):
print("❌ Nginx sites-enabled目录不存在")
return
for conf_file in os.listdir(self.nginx_enabled):
if conf_file.endswith(".conf"):
filepath = os.path.join(self.nginx_enabled, conf_file)
try:
with open(filepath, 'r') as f:
content = f.read()
# 提取server_name
if 'server_name' in content:
for line in content.split('\n'):
if 'server_name' in line:
name = line.split('server_name')[1].strip().rstrip(';')
print(f" • {name}")
break
except:
print(f" • {conf_file} (无法读取)")
def main():
manager = NginxReverseProxyManager()
if not manager.check_nginx():
sys.exit(1)
print("=" * 60)
print(" 🌐 Nginx反向代理配置工具")
print("=" * 60)
while True:
print("\n请选择操作:")
print("1. 添加反向代理")
print("2. 删除反向代理")
print("3. 查看所有配置")
print("4. 退出")
choice = input("\n请输入选项 (1-4): ").strip()
if choice == "1":
print("\n📝 添加反向代理配置")
server_name = input("域名 (如: example.com): ").strip()
proxy_pass = input("后端服务地址 (如: http://127.0.0.1:8080): ").strip()
port = input("监听端口 (默认80): ").strip() or "80"
ssl_choice = input("是否启用SSL? (y/n): ").strip().lower()
ssl = ssl_choice == 'y'
cert_path = ""
key_path = ""
if ssl:
cert_path = input("SSL证书路径: ").strip()
key_path = input("SSL密钥路径: ").strip()
manager.add_proxy(server_name, proxy_pass, int(port), ssl)
elif choice == "2":
print("\n🗑️ 删除反向代理配置")
server_name = input("要删除的域名: ").strip()
confirm = input(f"确认删除 {server_name} 的配置? (y/n): ").strip().lower()
if confirm == 'y':
manager.remove_proxy(server_name)
elif choice == "3":
manager.list_proxies()
elif choice == "4":
print("👋 再见!")
break
else:
print("❌ 无效选项,请重新选择")
if __name__ == "__main__":
main()
快速配置脚本(单命令行配置)
#!/bin/bash
# auto-nginx-proxy.sh - 快速配置Nginx反向代理
set -e
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
usage() {
echo "用法: $0 [选项]"
echo "选项:"
echo " -d DOMAIN 域名 (必填)"
echo " -p PROXY_PASS 后端服务地址 (必填, 如 http://localhost:3000)"
echo " -P PORT 监听端口 (默认80)"
echo " -s 启用HTTPS"
echo " -c CERT_PATH SSL证书路径 (HTTPS时需要)"
echo " -k KEY_PATH SSL密钥路径 (HTTPS时需要)"
echo " -r 只查看当前配置"
echo " -R DOMAIN 删除指定域名的配置"
echo " -h 显示帮助信息"
exit 1
}
# 检查Nginx
check_nginx() {
if ! command -v nginx &> /dev/null; then
echo -e "${RED}错误: Nginx未安装${NC}"
exit 1
fi
}
# 测试配置
test_config() {
echo -e "${YELLOW}测试Nginx配置...${NC}"
if nginx -t 2>&1; then
echo -e "${GREEN}配置测试通过${NC}"
return 0
else
echo -e "${RED}配置测试失败${NC}"
return 1
fi
}
# 重载Nginx
reload_nginx() {
echo -e "${YELLOW}重载Nginx...${NC}"
if nginx -s reload 2>&1; then
echo -e "${GREEN}Nginx已重载${NC}"
else
echo -e "${RED}Nginx重载失败${NC}"
exit 1
fi
}
# 添加配置
add_proxy() {
local domain=$1
local proxy_pass=$2
local port=$3
local ssl=$4
local cert=$5
local key=$6
config_file="/etc/nginx/sites-available/${domain}.conf"
if [ "$ssl" = true ]; then
# HTTPS配置
cat > "$config_file" << EOF
server {
listen ${port} ssl http2;
server_name ${domain};
ssl_certificate ${cert};
ssl_certificate_key ${key};
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
access_log /var/log/nginx/${domain}_access.log;
error_log /var/log/nginx/${domain}_error.log;
location / {
proxy_pass ${proxy_pass};
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection "upgrade";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
server {
listen 80;
server_name ${domain};
return 301 https://\$server_name\$request_uri;
}
EOF
else
# HTTP配置
cat > "$config_file" << EOF
server {
listen ${port};
server_name ${domain};
access_log /var/log/nginx/${domain}_access.log;
error_log /var/log/nginx/${domain}_error.log;
location / {
proxy_pass ${proxy_pass};
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection "upgrade";
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
EOF
fi
# 启用配置
ln -sf "$config_file" "/etc/nginx/sites-enabled/${domain}.conf"
echo -e "${GREEN}配置已创建: ${config_file}${NC}"
}
# 删除配置
remove_proxy() {
local domain=$1
if [ -f "/etc/nginx/sites-available/${domain}.conf" ]; then
rm -f "/etc/nginx/sites-enabled/${domain}.conf"
rm -f "/etc/nginx/sites-available/${domain}.conf"
echo -e "${GREEN}已删除 ${domain} 的配置${NC}"
else
echo -e "${RED}未找到 ${domain} 的配置${NC}"
fi
}
# 列出配置
list_proxies() {
echo -e "${YELLOW}当前反向代理配置:${NC}"
echo "----------------------------------------"
if [ -d "/etc/nginx/sites-enabled" ]; then
for conf in /etc/nginx/sites-enabled/*.conf; do
if [ -f "$conf" ]; then
domain=$(basename "$conf" .conf)
echo " • ${domain}"
fi
done
fi
}
# 主逻辑
main() {
check_nginx
if [ $# -eq 0 ]; then
usage
fi
# 解析参数
while getopts "d:p:P:sc:k:rR:h" opt; do
case $opt in
d) DOMAIN="$OPTARG" ;;
p) PROXY_PASS="$OPTARG" ;;
P) PORT="$OPTARG" ;;
s) SSL=true ;;
c) CERT_PATH="$OPTARG" ;;
k) KEY_PATH="$OPTARG" ;;
r) list_proxies; exit 0 ;;
R) remove_proxy "$OPTARG"; reload_nginx; exit 0 ;;
h) usage ;;
*) usage ;;
esac
done
# 如果只是查看配置,不需要其他参数
if [ -n "$DOMAIN" ] && [ -n "$PROXY_PASS" ]; then
PORT=${PORT:-80}
if [ "$SSL" = true ] && [ -z "$CERT_PATH" ] && [ -z "$KEY_PATH" ]; then
echo -e "${RED}启用HTTPS需要提供证书路径 (-c) 和密钥路径 (-k)${NC}"
exit 1
fi
add_proxy "$DOMAIN" "$PROXY_PASS" "$PORT" "${SSL:-false}" "$CERT_PATH" "$KEY_PATH"
if test_config; then
reload_nginx
else
echo -e "${RED}配置错误,正在回滚...${NC}"
remove_proxy "$DOMAIN"
reload_nginx
fi
fi
}
main "$@"
使用方法
Python脚本使用:
# 运行交互式脚本 sudo python3 nginx-proxy-manager.py # 添加反向代理 sudo python3 nginx-proxy-manager.py --add example.com http://localhost:3000 # 删除反向代理 sudo python3 nginx-proxy-manager.py --remove example.com
Bash脚本使用:
# 添加HTTP反向代理 sudo ./auto-nginx-proxy.sh -d example.com -p http://localhost:3000 # 添加HTTPS反向代理 sudo ./auto-nginx-proxy.sh -d example.com -p http://localhost:3000 -s -c /path/to/cert.pem -k /path/to/key.pem # 指定端口 sudo ./auto-nginx-proxy.sh -d example.com -p http://localhost:3000 -P 8080 # 查看所有配置 sudo ./auto-nginx-proxy.sh -r # 删除配置 sudo ./auto-nginx-proxy.sh -R example.com
安装依赖
# Debian/Ubuntu sudo apt-get update sudo apt-get install nginx python3 # CentOS/RHEL sudo yum install epel-release sudo yum install nginx python3
这些脚本提供了完整的Nginx反向代理配置功能,支持HTTP/HTTPS、WebSocket、负载均衡等特性,根据需要选择适合的版本使用。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播