2020 年在 Nginx 中强制使用 HTTPS 的最有效方法

2020 年在 Nginx 中强制使用 HTTPS 的最有效方法

我想要在 Nginx 中将 www 和 http 重定向到 https。

关于如何最好地做到这一点,网络上有很多意见,多年来最佳实践似乎已经发生了变化。我尝试了一些方法,所有这些方法似乎都有效,这让我有些担心。我想以最有效和最被接受的方式来做这件事。2020 年有没有什么强有力的共识?

这是我目前正在使用的。也欢迎任何其他建议。我使用 Let's Encrypt 进行认证,部分代码由 certbot 自动添加。

server {
  server_name www.example.com;
  return 301 $scheme://example.com$request_uri;
}

server {
  server_name example.com;
  root /var/www/mysite/public_html;
  index index.php index.html index.htm index.nginx-debian.html;
  access_log off;
  error_page 404 http://example.com;

  location / {
    try_files $uri $uri/ /index.php?$uri&$args;
  }

  location ~ \.php$ {
    fastcgi_pass unix:/run/php/php7.3-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    include snippets/fastcgi-php.conf;
  }

  location /secret/ {
    internal;
  }

  location /hidden/ {
    internal;
  }

  # A long browser cache lifetime can speed up repeat visits to your page
  location ~* \.(jpg|jpeg|gif|png|webp|svg|woff|woff2|ttf|css|js|ico|xml)$ {
    access_log off;
    log_not_found off;
    expires 360d;
  }

  # Disable access to dot files LetsEncrypt needs access to well-known
  location ~ /\.(?!well-known).* {
    deny all;
    access_log off;
    log_not_found off;
    return 404;
  }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot



}


server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


  listen 80;
  listen [::]:80;
  server_name example.com;
    return 404; # managed by Certbot


}

答案1

实施 HTTPS 重定向应遵循现代安全建议。在 99% 的情况下,您希望这与 HSTS 标头实施一致。

你可能想看看这里

通过适当的重定向链,您可以安全地实施 HSTS,这是许多人在应用 HTTPS 重定向时错过的。

具有包括前缀的规范 URL 的网站的示例配置www.

server {
    listen 80; 
    server_name example.com;
    return 301 https://example.com$request_uri;
}
server {
    listen 443 ssl http2;
    more_set_headers "Strict-Transport-Security: max-age=31536000; includeSubDomains; preload";
    ssl_certificate ...;
    ssl_certificate_key ...;
    server_name  example.com;
    return 301 https://www.example.com$request_uri;
}
server {
    listen 80; 
    server_name www.example.com;
    return 301 https://www.example.com$request_uri;
}
server {
    listen 443 ssl http2;
    more_set_headers "Strict-Transport-Security: max-age=31536000; includeSubDomains; preload";
    ssl_certificate ...;
    ssl_certificate_key ...;
    server_name www.example.com;
    ... main website directives go here
}

这里重要的是,当我们登陆时example.com:80,我们首先重定向到它的安全版本example.com:443,然后才到www.example.com:443

这使得重定向链example.com首先“覆盖”整个域用于安全通信的信息。

相关内容