Nginx静态资源服务

109 阅读2分钟

Nginx静态资源服务

1. 基础配置

创建Nginx配置文件(如/etc/nginx/conf.d/static.conf):

server {
    listen 80;
    server_name example.com;
    root /var/www/static;

    # 默认处理规则
    location / {
        try_files $uri $uri/ =404;
        # 禁止访问隐藏文件
        location ~ /\. { deny all; access_log off; log_not_found off; }
    }
}

2. 文件类型优化

# 图片缓存策略
location ~* \.(jpg|jpeg|png|gif|ico|svg|webp)$ {
    expires 365d;  # 缓存一年
    add_header Cache-Control "public, immutable";
    access_log off;  # 关闭日志
    # 启用WebP自动检测(若支持)
    if ($http_accept ~* "webp") {
        add_header Vary Accept;
    }
}

# 文本类文件缓存策略
location ~* \.(html|css|js|txt|xml)$ {
    expires 24h;
    add_header Cache-Control "public, must-revalidate";
}

# 字体文件
location ~* \.(woff2?|ttf|eot|otf)$ {
    expires 365d;
    add_header Cache-Control "public";
}

3. 传输优化配置

# 开启高效传输模式
sendfile on;
tcp_nopush on;     # 配合sendfile提升网络效率
tcp_nodelay on;    # 禁用Nagle算法,提升小文件响应
keepalive_timeout 65;

# Gzip压缩配置
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss image/svg+xml;
gzip_min_length 1024;  # 小于1KB不压缩
gzip_disable "msie6";  # 旧版IE不启用

# 文件访问缓存优化
open_file_cache max=1000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors off;

4. 安全增强

# 禁止非法User-Agent访问
if ($http_user_agent ~* (wget|curl|nikto|sqlmap)) {
    return 403;
}

# 防盗链配置
location ~* \.(jpg|png|gif)$ {
    valid_referers none blocked example.com *.example.com;
    if ($invalid_referer) {
        return 403;
        # 或重写到默认图片
        # rewrite ^ /static/denied.jpg;
    }
}

5. 部署步骤

  1. 创建目录并设置权限

    sudo mkdir -p /var/www/static
    sudo chown -R nginx:nginx /var/www/static
    sudo chmod -R 755 /var/www/static
    
  2. 放置静态文件: 将HTML、图片等资源放入/var/www/static目录。

  3. 验证并重载配置

    sudo nginx -t        # 检查语法
    sudo systemctl reload nginx  # 应用配置
    

6. 验证优化效果

使用curl检查响应头:

curl -I http://example.com/image.jpg

应看到以下关键头信息:

HTTP/1.1 200 OK
Cache-Control: public, immutable
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Content-Encoding: gzip  # 文本类资源可见

高级优化建议

  • HTTP/2支持:在SSL配置中启用http2
  • Brotli压缩:安装Brotli模块替代Gzip
  • CDN集成:将静态资源推送到CDN加速
  • 监控调优:使用ngx_http_stub_status_module监控性能指标

此配置在保证安全性的前提下,通过缓存策略、传输优化和压缩技术显著提升静态资源加载速度。建议根据实际业务需求调整缓存时间和压缩级别。