Hugo博客公告弹窗

Caddy 模块化配置:按需引入,各取所需

问题

多个场景(多项目)配置重复冗余,维护困难。

结尾贴出配置

解决方案

三种配置模块,按需组合:

(main_backend)    # 双后端负载均衡
(common_config)   # 通用安全配置
(standard_site)   # 组合上述两者

应用场景

场景一:标准站点(需要负载均衡)

www.2345.com {
    import standard_site  # 双后端 + 安全配置
}

场景二:单独服务器,不需要负载均衡

www.456.cc {
    reverse_proxy 192.168.100.3:80  # 专用后端
    import common_config             # 复用安全配置
}

场景三:简单重定向

2345.com {
    redir https://www.2345.com{uri} permanent  # 无需额外配置
}

场景四:HTTP批量重定向

http://456g.cc, http://www.456g.cc {
    redir https://www.456.cc{uri} permanent  # 多域名一次性配置
}

查看日志

(前 20 的访问统计):

cat /var/log/caddy/global.log | jq -r '.request.remote_ip' | sort | uniq -c | sort -nr | head -20

配置分享

https://github.com/woniu336/open_shell/blob/main/Caddyfile

# ===========================================
# 可复用配置片段
# ===========================================

# 主要后端配置
(main_backend) {
	reverse_proxy {
		to 192.168.100.1:80 192.168.100.2:80
		lb_policy round_robin
		lb_try_duration 30s
		lb_try_interval 250ms
		fail_duration 30s
		max_fails 3
		unhealthy_status 5xx
	}
}

# 通用配置
(common_config) {
	tls {
		protocols tls1.2 tls1.3
	}
	header {
		Permissions-Policy interest-cohort=()
		Strict-Transport-Security max-age=31536000;
		X-Content-Type-Options nosniff
		Referrer-Policy strict-origin-when-cross-origin
		X-XSS-Protection "1; mode=block"
		-Via
		-Alt-Svc
		-Server
	}
	handle_errors {
		@5xx expression {http.error.status_code} >= 500
		respond @5xx "服务暂时不可用,请稍后重试" 503
		@4xx expression {http.error.status_code} >= 400
		respond @4xx "请求错误" {http.error.status_code}
	}
	log {
		output file /var/log/caddy/global.log {
			roll_size 50mb
			roll_keep 5
		}
	}
}

# 标准站点配置
(standard_site) {
	import main_backend
	import common_config
}

# ===========================================
# 站点配置
# ===========================================

2345.com {
	redir https://www.2345.com{uri} permanent
}

www.2345.com {
	import standard_site
}

789.cc {
	redir https://www.789.cc{uri} permanent
}

www.789.cc {
	import standard_site
}

456.cc {
	redir https://www.456.cc{uri} permanent
}

www.456.cc {
	import common_config
	reverse_proxy 192.168.100.3:80
}

http://456g.cc, http://www.456g.cc {
	redir https://www.456.cc{uri} permanent
}
CC BY-NC-SA 4.0 转载请注明
最后更新于 2025-08-24 04:18
clarity统计