在Nginx中优化静态文件访问是提升网站响应速度的关键。以下是一个基础的静态文件配置示例:
server {
listen 80;
server_name example.com;
location /static/ {
alias /path/to/your/static/files/;
# 启用高效文件传输
sendfile on;
tcp_nopush on;
# 设置缓存头
expires 30d;
add_header Cache-Control "public";
# 启用gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml;
}
}
sendfile on;
tcp_nopush on;
sendfile
允许Nginx直接在内核空间传输文件,减少用户空间和内核空间之间的数据拷贝tcp_nopush
与sendfile
一起使用,确保数据包填满后再发送expires 30d;
add_header Cache-Control "public";
public
允许代理服务器缓存内容gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_min_length 1024;
gzip_comp_level 6;
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
location /hot-static/ {
alias /dev/shm/hot-static/;
# 其他配置...
}
location /static/ {
proxy_cache STATIC;
proxy_cache_valid 200 30d;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
}
listen 443 ssl http2;
brotli on;
brotli_types text/plain text/css application/json application/javascript text/xml;
配置完成后,使用以下工具测试效果:
1. ab
(Apache Benchmark)
2. wrk
3. siege
4. WebPageTest 或 Lighthouse
通过以上优化,可以显著提升静态文件的访问速度,降低服务器负载,改善用户体验。