nginx 如何在配置文件给静态文件添加缓存
2024-5-23 杜世伟
在 Nginx 中为静态文件添加缓存可以通过设置响应头来实现。这可以通过在 Nginx 配置文件中使用 expires 指令来完成。以下是一个示例配置,展示了如何为特定类型的静态文件(如图像、CSS、JavaScript 文件等)设置缓存头。
假设你的 Nginx 配置文件路径是 /etc/nginx/nginx.conf,你可以在其中添加或修改 server 块来包含缓存配置:
http {
# 其他全局配置
server {
listen 80;
server_name example.com;
root /var/www/html;
location / {
try_files $uri $uri/ =404;
}
# 为图像文件设置缓存
location ~* \.(jpg|jpeg|png|gif|ico|bmp|webp)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
# 为CSS和JavaScript文件设置缓存
location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public, no-transform";
}
# 为字体文件设置缓存
location ~* \.(woff|woff2|ttf|otf|eot)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
# 为SVG文件设置缓存
location ~* \.(svg|svgz)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
# 其他静态文件
location ~* \.(html|htm)$ {
expires 1h;
add_header Cache-Control "public, no-transform";
}
# 其他配置...
}
}
在上述配置中:
expires 指令用于设置过期时间,30d 表示30天,7d 表示7天,1h 表示1小时。
add_header Cache-Control 指令用于设置 Cache-Control 响应头,public, no-transform 表示允许所有缓存,且在缓存时不进行转换。
sudo nginx -s reload
这样,Nginx 将为匹配的静态文件添加缓存头,帮助浏览器和中间缓存服务器更好地缓存这些文件,从而提高性能。
热门日志
分类
- Django(4)
- ssdb(1)
- Mac(7)
- C(1)
- memcache(1)
- Python(32)
- Vim(8)
- sed(2)
- ansible(3)
- awk(4)
- shell(3)
- about(1)
- git(9)
- bat(4)
- svn(0)
- docker(1)
- Tornado(1)
- go(2)
- 架构(18)
- Vue(1)
- game(2)
- Html(6)
- Java(8)
- Mysql(37)
- Ajax(2)
- Jsp(1)
- Struts(8)
- Linux(72)
- JavaScript(39)
- Staruml(0)
- Mouth(1)
- Php(102)
- Windows(8)
- Message(48)
- Lua(10)
- Compute(1)
- Redis(7)
- Nginx(12)
- Jquery(1)
- Apache(1)
- cocos2d-x(8)