欢迎光临上海华金科技
马上发布信息
详情描述
Nginx静态资源优化、压缩、缓存详解
Nginx静态资源优化、压缩、缓存详解

一、基础配置与性能优化

1. 连接与进程优化

# nginx.conf主配置
worker_processes auto;  # 自动根据CPU核心数设置
worker_rlimit_nofile 65535;  # 每个worker能打开的最大文件数

events {
    worker_connections 10240;  # 每个worker的最大连接数
    use epoll;  # Linux下使用epoll高效模型
    multi_accept on;  # 一次接受多个连接
}

2. HTTP基础优化

http {
    # 基础优化
    sendfile on;  # 启用sendfile系统调用
    tcp_nopush on;  # 在sendfile模式下启用,提高网络包传输效率
    tcp_nodelay on;  # 禁用Nagle算法,减少延迟

    # 连接超时设置
    keepalive_timeout 65;
    keepalive_requests 100;
    client_header_timeout 15s;
    client_body_timeout 15s;
    send_timeout 15s;

    # 隐藏Nginx版本号
    server_tokens off;
}

二、静态资源压缩配置

1. Gzip压缩配置

http {
    # Gzip基础配置
    gzip on;
    gzip_vary on;
    gzip_comp_level 6;  # 压缩级别1-9,6是平衡点
    gzip_buffers 16 8k;
    gzip_min_length 1024;  # 小于1KB不压缩
    gzip_proxied any;  # 对所有代理请求启用压缩
    gzip_disable "msie6";  # 对IE6禁用

    # 压缩类型
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/xhtml+xml
        application/font-woff
        application/font-woff2
        image/svg+xml;
}

2. Brotli压缩(需要Nginx模块支持)

# 需要安装ngx_brotli模块
brotli on;
brotli_comp_level 6;
brotli_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/json
    application/javascript
    application/xml+rss
    image/svg+xml;
brotli_static on;  # 预压缩静态文件

3. 预压缩静态文件

# 生成预压缩文件
gzip -k -9 style.css  # 生成style.css.gz
brotli -k -q 11 style.css  # 生成style.css.br
# 配置预压缩文件服务
location ~ \.(css|js|html|svg|txt)$ {
    gzip_static on;  # 优先使用预压缩文件
    brotli_static on;
}

三、缓存策略配置

1. 浏览器缓存(客户端缓存)

location ~* \.(jpg|jpeg|png|gif|ico|svg|webp)$ {
    # 图片类资源,可缓存较长时间
    expires 365d;
    add_header Cache-Control "public, immutable";
    add_header Pragma public;

    # 添加缓存校验头
    add_header Last-Modified "";
    if_modified_since off;
}

location ~* \.(css|js)$ {
    # CSS/JS文件,使用版本号控制缓存
    expires 30d;
    add_header Cache-Control "public, max-age=2592000";

    # 版本化文件(带hash)可以永久缓存
    location ~* \.[a-f0-9]{8}\.(css|js)$ {
        expires max;
        add_header Cache-Control "public, immutable, max-age=31536000";
    }
}

location ~* \.(woff|woff2|ttf|eot)$ {
    # 字体文件永久缓存
    expires max;
    add_header Cache-Control "public, immutable, max-age=31536000";
    add_header Access-Control-Allow-Origin "*";
}

2. 代理缓存(服务器端缓存)

# 定义缓存路径和参数
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=static_cache:10m 
                 max_size=1g inactive=60m use_temp_path=off;

# 静态资源缓存配置
location /static/ {
    proxy_cache static_cache;
    proxy_cache_key "$scheme$request_method$host$request_uri";
    proxy_cache_valid 200 304 12h;
    proxy_cache_valid 301 302 1h;
    proxy_cache_valid any 1m;

    # 缓存锁定(防止缓存击穿)
    proxy_cache_lock on;
    proxy_cache_lock_timeout 5s;

    # 缓存状态头(调试用)
    add_header X-Cache-Status $upstream_cache_status;

    # 缓存条件
    proxy_cache_revalidate on;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    proxy_cache_background_update on;

    # 源站配置
    proxy_pass http://backend;
}

四、文件服务优化

1. 优化静态文件服务

location /assets/ {
    # 基础文件服务配置
    root /var/www;

    # 目录访问控制
    autoindex off;

    # 优化文件查找
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # 零拷贝技术
    sendfile on;
    directio 4m;  # 大文件使用直接IO
    aio on;  # 异步IO

    # 输出缓冲区优化
    output_buffers 1 512k;
}

2. 大文件传输优化

location /downloads/ {
    # 大文件分片传输
    slice 1m;  # 每片1MB
    proxy_set_header Range $slice_range;
    proxy_cache_key $uri$slice_range;

    # 限速(带宽控制)
    limit_rate_after 10m;  # 前10MB不限速
    limit_rate 100k;  # 之后限速100KB/s

    # 断点续传支持
    proxy_cache_valid 206 1h;
}

五、安全与访问控制

1. 访问控制

location ^~ /protected/ {
    # 基本认证
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;

    # IP限制
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;

    # 限流
    limit_req zone=static_zone burst=5 nodelay;
}

# 定义限流区域
limit_req_zone $binary_remote_addr zone=static_zone:10m rate=10r/s;

2. 防盗链配置

location ~* \.(jpg|jpeg|png|gif)$ {
    # 允许的域名
    valid_referers none blocked server_names
                  ~\.google\. ~\.baidu\. ~\.qq\.
                  *.example.com;

    if ($invalid_referer) {
        # 返回403或替换图片
        return 403;
        # rewrite ^ /images/403.png;
    }
}

六、高级优化技巧

1. HTTP/2 优化

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    # HTTP/2优化
    http2_push_preload on;
    http2_max_concurrent_streams 128;

    # SSL优化(启用HTTP/2必须)
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
}

2. 多级缓存策略

# 定义多级缓存
proxy_cache_path /data/nginx/cache_1 levels=1:2 keys_zone=cache_1:10m max_size=10g;
proxy_cache_path /data/nginx/cache_2 levels=1:2 keys_zone=cache_2:10m max_size=1g;

location / {
    # 第一级缓存:热数据
    proxy_cache cache_1;
    proxy_cache_key "$scheme$host$request_uri$is_args$args";
    proxy_cache_valid 200 302 10m;

    # 第二级缓存:温数据
    proxy_cache cache_2;
    proxy_cache_valid 200 302 1h;
}

3. 智能缓存清理

#!/bin/bash
# 缓存清理脚本
CACHE_PATH="/var/cache/nginx"

# 清理特定前缀的缓存
find $CACHE_PATH -type f -name "*.css*" -mtime +7 -delete
find $CACHE_PATH -type f -name "*.js*" -mtime +15 -delete

# 重新加载Nginx
nginx -s reload

七、监控与调试

1. 缓存状态监控

# 缓存状态接口
location /nginx-cache-status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

# 添加缓存头信息(便于调试)
add_header X-Cache $upstream_cache_status;
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;

2. 日志配置优化

# 分离静态资源日志
map $uri $loggable {
    ~\.(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ 0;
    default 1;
}

access_log /var/log/nginx/access.log combined if=$loggable;
access_log /var/log/nginx/static.log combined buffer=32k flush=5s if=!$loggable;

八、完整配置示例

# 完整静态资源服务器配置示例
server {
    listen 80;
    server_name static.example.com;

    root /var/www/static;
    index index.html;

    # 压缩配置
    gzip on;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript;

    # 缓存配置
    location ~* \.(css|js)$ {
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
    }

    location ~* \.(jpg|jpeg|png|gif|ico|svg)$ {
        expires 365d;
        add_header Cache-Control "public, immutable";
    }

    location ~* \.(woff|woff2|ttf|eot)$ {
        expires max;
        add_header Cache-Control "public, immutable, max-age=31536000";
        add_header Access-Control-Allow-Origin "*";
    }

    # 文件服务优化
    location / {
        try_files $uri $uri/ =404;
        open_file_cache max=1000 inactive=20s;
        open_file_cache_valid 30s;
    }

    # 防盗链
    location ~ \.(jpg|jpeg|png|gif)$ {
        valid_referers blocked server_names ~\.google\. ~\.baidu\.;
        if ($invalid_referer) {
            return 403;
        }
    }

    # 访问日志(排除静态资源)
    access_log /var/log/nginx/static-access.log combined buffer=32k flush=5s;

    # 错误页面
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
}

九、性能测试与验证

1. 测试压缩效果

# 检查Gzip是否生效
curl -H "Accept-Encoding: gzip" -I http://example.com/style.css

# 检查缓存头
curl -I http://example.com/image.jpg

# 压力测试
ab -n 1000 -c 100 http://example.com/

2. 监控指标

# 添加性能监控头
add_header X-Response-Time $request_time;
add_header X-Upstream-Response-Time $upstream_response_time;
add_header X-Request-ID $request_id;

十、最佳实践总结

压缩策略

  • 对小文件启用gzip压缩
  • 对大文件使用预压缩
  • 动态内容压缩等级设为6

缓存策略

  • 版本化资源使用immutable缓存
  • 非版本化资源使用协商缓存
  • 图片字体类资源长期缓存

性能优化

  • 启用sendfile和tcp_nopush
  • 使用open_file_cache缓存文件描述符
  • 合理设置worker_processes和connections

安全考虑

  • 配置防盗链
  • 设置访问控制
  • 隐藏服务器信息

监控维护

  • 定期清理过期缓存
  • 监控缓存命中率
  • 分析访问日志优化配置

通过合理的Nginx配置,静态资源的加载速度可以提升数倍,显著改善网站性能和用户体验。建议根据实际业务需求调整各项参数,并通过监控工具持续优化。