【问题标题】:Reduce duplication in Nginx site-conf files减少 Nginx 站点配置文件中的重复
【发布时间】:2019-05-06 17:05:42
【问题描述】:

以下代码在我所有的 Nginx 站点配置文件 (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;
    }
}

【问题讨论】:

  • location 指令需要在 server 块内。为避免跨多个域名重复,请使用include 指令或使用正则表达式server_name
  • 理查德,请在我的回答中查看更新。
  • @fayalikt sudo nginx -t 应该测试所有配置文件并返回错误和警告位置。
  • 正则表达式服务器名称为documented here。您也许可以用单个块替换现有的服务器块。您不能将位置块继承到多个服务器中(除非您可以使用包含)。
  • 不同域的变化部分是什么?

标签: nginx


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 2013-08-29
    • 1970-01-01
    • 2012-10-15
    • 2011-05-27
    • 2015-05-21
    • 2016-04-22
    相关资源
    最近更新 更多