在 nginx 配置文件中,重复性配置的复用方法
比如在一个 nginx 服务器中配置了多个二级域名,可能有一些关于 SSL 和其它安全 Header 的配置是大量重复的
每次添加或修改的话,都需要手动复制或替换很多地方,容易疏漏
可以将相同的配置统一写在一个文件中,在各处使用 include 引用即可。
1、新建一个文件,将所需配置存入其中(如保存至文件 /home/shared.conf)
listen 443 ssl;
listen [::]:443 ssl;
root e:/projects/TheVegCat/src/main/resources/static/;
ssl_certificate e:/projects/TheVegCat/ssl/CA/localhost/localhost.crt;
ssl_certificate_key e:/projects/TheVegCat/ssl/CA/localhost/localhost.decrypted.key;
add_header Strict-Transport-Security "max-age=10368000; includeSubDomains" always;
gzip on;
gzip_min_length 512;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain application/xml text/css application/javascript application/json;
location ~ ^(.+)\.(ico|png|xml|json)$ {
expires 1y;
alias e:/projects/TheVegCat/src/main/resources/static/favicon/;
try_files $1.$2 $1.$2/;
}
2、在 nginx.conf 中,使用 include 引用即可(路径不限)
server {
server_name localhost thevegcat.lan;
include /home/shared.conf;
location / {
add_header Strict-Transport-Security "max-age=10368000; includeSubDomains" always;
proxy_pass http://localhost:8080;
}
}
server {
server_name veganskivodic.thevegcat.lan;
include /home/shared.conf;
location / {
add_header Strict-Transport-Security "max-age=10368000; includeSubDomains" always;
proxy_pass http://veganskivodic.thevegcat.lan:8080;
}
}
参考:https://serverfault.com/questions/1125363/avoid-duplicate-nginx-server-definition
输了你,赢了世界又如何...