最小化和优化 NGINX 虚拟主机配置



是否可以优化/最小化下面发布的配置?

我觉得应该可以将所有重定向合并为更简单的内容。

http://& http://www & https://www> https://

虽然我遇到了问题并解决了。

我知道 NGINX 配置中不支持变量,因此我必须手动定义日志位置。有没有办法为所有虚拟主机设置默认位置?

我对所有虚拟主机使用相同的ssl-params.conf文件。是否可以基于每个主机进行默认和禁用此功能?

# Redirect http:// & http://www to https://
server {
  server_name example.com www.example.com;
  return 301 https://example.com$request_uri;
}
# Redirect https://www to https://
server {
  listen 443 ssl;
  server_name www.example.com;
  return 301 https://example.com/$request_uri;
}
# Main config
server {
  listen 443 ssl;
  server_name example.com;
  # SSL config
  include snippets/ssl-example.com.conf;
  include snippets/ssl-params.conf;
  # Error logs
  access_log /srv/logs/nginx.access.example.com.log;
  error_log srv/logs/nginx.error.example.com.log;
  # Root dir
  location / {
    root /srv/example.com/_site/;
    index index.php index.html index.htm;
    try_files $uri $uri/ /index.php?$args;
  }
  # Caching
  location ~ .php$ {
    root /srv/example.com/_site/;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  }
  location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
    root /srv/example.com/_site/;
    expires 365d;
  }
  location ~*  .(pdf)$ {
    root /srv/example.com/_site/;
    expires 30d;
  }
  # SSL
  location /.well-known {
    allow all;
  }
}

我知道 NGINX 配置中不支持变量,因此我必须手动定义日志位置。有没有办法为所有虚拟主机设置默认位置?

是的,只需在配置的http上下文中定义它,或者坚持使用发行版的默认值(例如 /var/log/nginx/access.log (。

我对所有虚拟主机使用相同的 ssl-params.conf 文件。是否可以基于每个主机进行默认和禁用此功能?

的工作方式相反,您可以通过 include 指令在您需要的地方启用它。


这是一个较短的配置(未经测试(:

http {
    error_log   /srv/logs/nginx.error.example.com.log;
    access_log  /srv/logs/nginx.access.example.com.log;
    index       index.php index.html index.htm;
    server {
        listen 80;
        listen 443 ssl;
        server_name .example.com;
        include snippets/ssl-example.com.conf;
        include snippets/ssl-params.conf;
        return 301 https://example.com$request_uri;
    }
    server {
        listen 443 ssl;
        server_name example.com;
        root /srv/example.com/_site/;
        include snippets/ssl-example.com.conf;
        include snippets/ssl-params.conf;
        location / {
            location ~ .php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                try_files $uri =404;
            }
            location ~* .(jpe?g|png|gif|ico|css|js)$ {
                expires 365d;
            }
            location ~* .(pdf)$ {
                expires 30d;
            }
            try_files $uri $uri/ /index.php?$args;
        }
        location /.well-known {
            allow all;
        }
    }
}