调校 Nginx

2025/11/01

用 Nginx 很长时间了,但是每次遇到问题还是要重新去查,踩过的一些坑现在记录一下,对抗遗忘。

ssl-options

记录一个好用的 ssl 配置。

# This file contains important security parameters. If you modify this file
# manually, Certbot will be unable to automatically provide future security
# updates. Instead, Certbot will print and log an error message with a path to
# the up-to-date file that you will need to refer to when manually updating
# this file. Contents are based on https://ssl-config.mozilla.org

ssl_session_cache shared:le_nginx_SSL:10m;
ssl_session_timeout 1440m;
ssl_session_tickets off;

ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;

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";

使用这个配置文件的时候,不需要 dhparams。

验证 cloudflare 的 origin pull

可以避免攻击者绕过 CDN 直接访问 web server,特别是在全 IP 爆破域名的情况下。

        ssl_verify_client optional;
        ssl_client_certificate certs/cloudflare_authenticated_origin_pull_ca.crt; 

        location / {
                if ($ssl_client_verify != SUCCESS) {
                        return 403;
                }

                try_files $uri $uri/ /404.html;
        }

保证不同 server name 的错误页面相同

这样做可以避免域名爆破。

        error_page 403 = @no_body;
        location @no_body {
                add_header Content-Type text/plain;
                return 403 '1';
        }

目标是保持所有的某个 HTTP 错误的 body 都一致,避免攻击者通过页面不一致来区分是否爆破到了一个域名。需要把每一个 vhost 的错误都按照上述的方法配置。