减少 Nginx 站点会议文件中的重复



下面的代码在我的所有Nginx站点conf文件中重复自己(sites-available/domain.tld.conf)。我可以有 50 个网站,所有 50 个站点会议文件都有相同的重复:

location / {
    index index.php index.html index.htm;
    try_files $uri $uri/ /index.php?$args;
}
location ~ .php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass 127.0.0.1:9000;
}
location ~ /.ht {
    deny all;
}
location ~*  .(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ {
    expires 365d;
}

有没有办法减少重复(无需取消include)?

也许,将这些放在全局nginx.conf文件中?

理查德·史密斯的更新:

将此服务器块放在 nginx.conf 的末尾会使服务器重新启动失败:

server {
    location / {
        index index.php index.html index.htm;
        try_files $uri $uri/ /index.php?$args;
    }
    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass 127.0.0.1:9000;
    }
    location ~ /.ht {
        deny all;
    }
    location ~*  .(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ {
        expires 365d;
    }
}

将所有重复配置放在一个单独的文件中并包含它。我更喜欢将其放在已知位置,并根据文件的主题对其进行拆分,例如:

include /etc/nginx/cache_static_files.conf ;
include /etc/nginx/proxy_to_php73_fpm.conf ;

注意:对包含的配置文件使用完整/绝对路径。

最新更新