Nginx常用配置片段
记录Nginx经常使用的代码片段

本文配置片段皆取自 https://github.com/NoyTeam/nginx-conf/ 欢迎Star✨

缓存配置

    proxy_cache_path /cache 
    levels=1:2:2
    keys_zone=cache_one:25M
    max_size=20G
    inactive=31d
    use_temp_path=ON;
  1. Proxy_Cache_Path: 缓存目录 e.g: /cache
  2. Levels: 缓存目录层级 e.g: 1:2=/cache/a/b2 1:2:2=/cache/c/d2/ef *层级越长可缓存的文件越多
  3. Keys_Zone: 单个缓存文件大小上限 e.g: 128K 10M 10G
  4. Max_Size: 总缓存文件大小上限 e.g: 10G 10T
  5. Inactive: 缓存器检查时间间隔 e.g: 10s 1h 1d *推荐 7~31天
  6. Use_Temp_Path: 是否启用临时缓存目录 *若不启用则为 off

压缩配置

Gzip

    gzip on;
    gzip_min_length  1k;
    gzip_comp_level 1;
    gzip_types text/plain application/x-javascript text/css application/xml text/javascript
    application/x-httpd-php application/javascript application/json;
    gzip_proxied   expired no-cache no-store private auth;
    gzip_vary on;
  1. Gzip_Min_Length: 字面意思,Gzip压缩的最低大小限制 e.g 1k 1m
  2. Gzip_Comp_Level: Gzip压缩等级,1~9级,其中推荐1级即可,等级再高效果就不佳了
  3. Gzip_Vary: 是否发送 vary header

Brotli

    brotli on;
    brotli_comp_level 4;
    brotli_static on;
    brotli_min_length 64k;

    brotli_types application/atom+xml application/javascript application/json application/rss+xml
             application/vnd.ms-fontobject application/x-font-opentype application/x-font-truetype
             application/x-font-ttf application/x-javascript application/xhtml+xml application/xml
             font/eot font/opentype font/otf font/truetype image/svg+xml image/vnd.microsoft.icon
             image/x-icon image/x-win-bitmap text/css text/javascript text/plain text/xml;
  1. Brotli_Comp_Level: Brotli 压缩层级 (1~11) 动态内容居多推荐配置为 4 ,静态内容配合 Brotli_Static 可配置为 11
  2. Brotli_Static: 若静态资源居多,则推荐开启
  3. Brotli_Min_Length: 文件大小大于此设定再进行压缩,避免小文件调用Brotli过度浪费资源

其他配置

Websocket

    map $http_upgrade $connection_upgrade {
        default upgrade;
        ""      close;
    }

自动添加 upgrade 标头

HSTS Header

HSTS: (HTTP Strict Transport Security)

    map $scheme $hsts_header {
    https   "max-age=31536000; includeSubDomains; preload";
    }
  1. Max-Age: HSTS生效时间,单位秒
  2. includeSubDomains: 包含所有子域名
  3. Preload HSTS Preload, https://hstspreload.org/

最后修改于 2022-06-18