通过 include 复用安全规则需将通用配置抽离为独立文件(如 /etc/nginx/conf.d/security-common.conf),并在各 server 块中用 include 指令引入,确保策略统一且免重复;支持用 map 配合变量实现按域名差异化控制,且 include 必须置于 server 或 http 块内,路径须为绝对路径。

用 include 在不同域名间复用安全限制规则,核心是把通用配置抽离成独立文件,再在各 server 块中统一引入。这样既避免重复写,又保证所有域名执行一致的安全策略。
把公共安全规则单独写进一个文件
比如新建 /etc/nginx/conf.d/security-common.conf,内容包括常用防护项:
-
add_header X-Frame-Options "DENY" always;(防点击劫持) -
add_header X-Content-Type-Options "nosniff" always;(阻止MIME类型嗅探) -
add_header X-XSS-Protection "1; mode=block" always;(启用XSS过滤) add_header Referrer-Policy "no-referrer-when-downgrade" always;-
client_max_body_size 10m;(限制上传大小) -
limit_req zone=global burst=10 nodelay;(全局请求限流,需提前定义 zone)
在每个 server 块里引用这个文件
不需要复制粘贴,只需在各个域名的 server 配置中加入一行:
include /etc/nginx/conf.d/security-common.conf;
例如两个域名分别配置:
server {<br> listen 443 ssl;<br> server_name app.example.com;<br> include /etc/nginx/conf.d/security-common.conf;<br> location / { proxy_pass http://backend-app; }<br>}
server {<br> listen 443 ssl;<br> server_name api.example.com;<br> include /etc/nginx/conf.d/security-common.conf;<br> location / { proxy_pass http://backend-api; }<br>}
配合 map 或变量做细粒度控制
如果某些规则需按域名差异化(比如只对后台域名加 X-Robots-Tag),可在 security-common.conf 中使用 map 定义变量,再在 server 块中条件启用:
map $host $is_admin_domain {<br> default 0;<br> "admin.example.com" 1;<br>}
然后在 security-common.conf 中写:if ($is_admin_domain) { add_header X-Robots-Tag "noindex, nofollow"; }
注意 include 的加载顺序和作用域
include 是文本级包含,位置决定生效范围:
- 放在
http块里 → 全局生效(适合限流 zone、日志格式等) - 放在
server块里 → 仅对该域名生效(推荐用于安全头) - 不能放在
if或location内部(语法不支持) - 路径必须绝对,相对路径会失败











