Nginx下的HTTPS优化

2,334 阅读1分钟

对网站安全可由👉SSL安全测试网站测试。以下配置测试为A+

添加HSTS预加载列表HSTS Preload List Submission注:谨慎操作,如果无法确保永远提供 HTTPS 服务,就不要启用,申请移出该列表需要数月之久。

配置参考

详细配置如下,基本上各个配置都注释了用途。

server
    {
        listen 80;
        server_name www.yezijun.top yezijun.top;
        rewrite ^(.*)$ https://$host$uri;
	}
server
    {
        listen 443 http2;
        server_name www.yezijun.top yezijun.top;
    
        # 开启ssl
        ssl on;
        ssl_certificate /etc/letsencrypt/live/yezijun.top/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/yezijun.top/privkey.pem;
    
        # 指定DNS配置
        resolver 223.5.5.5 223.6.6.6 valid=60s;
        resolver_timeout 2s;
    
        # DHE密码器的Diffie-Hellman参数,需要openssl手动生成
        # openssl命令:openssl dhparam 2048 -out dhparam.pem
        ssl_dhparam /etc/letsencrypt/live/yezijun.top/dhparam.pem;
    
        # 开启OCSP Stapling,由服务器验证证书在线状态,提高TLS握手效率
        ssl_stapling on;
        ssl_stapling_verify on;
    
        # 开启HSTS,缓存http重定向到https,以防止中间人攻击
        # 不包含子域(宝塔界面是http的)
        # 不预加载(预加载要在https://hstspreload.org/中添加)
        add_header Strict-Transport-Security "max-age=63072000;" always;
    
        # 开启TLS False Start
        ssl_prefer_server_ciphers on;
    
        # 中等兼容程度,Mozilla推荐配置
        # 文档 => https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
        ssl_ciphers  ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    
        # 中等兼容程度,Mozilla推荐配置
        ssl_protocols TLSv1.2 TLSv1.3;
    
        # 由客户端保存加密后的session信息
        ssl_session_tickets on;
    
        # 缓存SSL
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 1d;
    
        # 长链接
        keepalive_timeout  70;
    
        #减少点击劫持,禁止在iframe中加载
        add_header X-Frame-Options DENY;
    
        # 根目录
        root /www/Light/Client/build;
        index index.html index.htm;
    
        # 针对history路由方式,路径匹配失败尝试匹配index
        location / {
          try_files $uri $uri/ /index.html;
        }
    
        # 反向代理后端接口,并强制转换成https
        location ~ /api/ {
          add_header Content-Security-Policy upgrade-insecure-requests;
          proxy_pass  http://localhost:5000;
        }
    
        # 静态资源长期强缓存
        location ^~ /static/media/ {
          gzip_static on;
          expires max;
          add_header Cache-Control public;
        }
    }

总结

以上仅用了HTTPS的一些常用优化方案,仍有不少细节可以继续优化,具体可以根据SSL安全测试网站的检查结果按需补充。