Skip to content

Instantly share code, notes, and snippets.

@llccing
Created April 18, 2024 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save llccing/66b97df2b5a1134166a155dc6280900f to your computer and use it in GitHub Desktop.
Save llccing/66b97df2b5a1134166a155dc6280900f to your computer and use it in GitHub Desktop.
#!/bin/bash
# 脚本用于自动化配置 Nginx 以支持 HTTPS 和 WebSocket (WSS)
# 新子域名
new_domain=$1
# 检查参数
if [ -z "$new_domain" ]; then
echo "Usage: $0 <newdomain.xindamate.com>"
exit 1
fi
# Nginx 配置文件路径
nginx_config="/etc/nginx/sites-available/xindamate.com"
nginx_link="/etc/nginx/sites-enabled/xindamate.com"
# 检查 Nginx 配置文件是否存在
if [ ! -f "$nginx_config" ]; then
echo "Nginx configuration file does not exist: $nginx_config"
exit 1
fi
# 更新 Nginx 配置
echo "Adding $new_domain to Nginx configuration."
cat << EOF >> $nginx_config
server {
listen 443 ssl;
server_name $new_domain;
ssl_certificate /etc/letsencrypt/live/xindamate.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/xindamate.com/privkey.pem;
location / {
proxy_pass http://localhost:8080; # 根据实际后端服务进行调整
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection "upgrade";
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;
}
}
# 这个也很重要,避免自己各种查找后发现是这个问题,即实际访问的是 http 非 https
server {
listen 80;
server_name $new_domain;
# 重定向所有 HTTP 流量到 HTTPS
return 301 https://$server_name$request_uri;
}
EOF
# 确保配置文件链接正确
if [ ! -L "$nginx_link" ]; then
ln -s $nginx_config $nginx_link
fi
# 测试 Nginx 配置
echo "Testing Nginx configuration."
nginx -t
if [ $? -ne 0 ]; then
echo "Nginx configuration test failed."
exit 1
fi
# 重新加载 Nginx
echo "Reloading Nginx."
nginx -s reload
# 使用 Certbot 更新 SSL 证书
echo "Updating SSL certificate for $new_domain."
certbot certonly --expand --cert-name xindamate.com -d xindamate.com,$new_domain --nginx
# 再次检查并重新加载 Nginx
nginx -t && nginx -s reload
echo "$new_domain has been configured successfully."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment