Files
openresty-gateway/scripts/ensure-domain-conf.sh
2026-05-18 22:32:08 +08:00

68 lines
1.9 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env sh
set -eu
# 为传入的域名生成基础 nginx 配置。
# 如果 conf/conf.d/xxx.conf 已经存在,直接跳过,避免覆盖人工维护的配置。
ROOT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
# 默认写入 openresty-gateway/conf/conf.d。
# 如需生成到其他目录,可以在执行前设置 CONF_DIR例如
# CONF_DIR="./conf/test.d" sh scripts/ensure-domain-conf.sh example.com
CONF_DIR="${CONF_DIR:-./conf/conf.d}"
cd "$ROOT_DIR"
# 必须显式传入域名,避免无参数执行时静默成功但什么都不做。
if [ "$#" -eq 0 ]; then
echo "用法sh scripts/ensure-domain-conf.sh <域名> [域名...]" >&2
exit 1
fi
ensure_domain_conf() {
domain="$1"
conf_file="$CONF_DIR/$domain.conf"
# 已存在的域名配置不重新生成,避免覆盖已有转发、限流、路径规则等自定义配置。
if [ -f "$conf_file" ]; then
echo "跳过已存在的 nginx 配置:$conf_file"
return
fi
# 这里只生成一个能响应 ACME webroot 校验的最小 HTTPS 站点模板。
# 业务代理规则可以后续在生成的 conf 文件里按需补充。
echo "创建 nginx 配置模板:$conf_file"
mkdir -p "$CONF_DIR"
cat > "$conf_file" <<EOF
server {
listen 80;
listen 443 ssl;
server_name $domain;
ssl_certificate /etc/letsencrypt/live/$domain/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/$domain/privkey.pem;
root /var/www/$domain;
index index.html;
location ^~ /.well-known/acme-challenge/ {
root /var/www;
default_type text/plain;
try_files \$uri =404;
}
location / {
if (\$scheme = http) {
return 301 https://\$host\$request_uri;
}
try_files \$uri \$uri/ /index.html;
}
}
EOF
}
for domain in "$@"; do
ensure_domain_conf "$domain"
done