Nginx设置静态页面压缩和缓存过期时间的方法

配置Gzip压缩
1、启用Gzip模块: 确保Nginx编译时包含Gzip模块。
2、修改Nginx配置文件: 在http块中添加以下代码,以启用Gzip压缩:
```nginx
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 1024;
gzip_proxied any;
gzip_buffers 16 8k;
gzip_http_version 1.1;
```
3、重启Nginx服务: 应用更改并重启Nginx。
```bash
sudo service nginx restart

```
设置缓存过期时间
1、配置缓存过期: 在server块或者location块中添加以下代码,以设置缓存过期时间:
```nginx
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
```
2、重启Nginx服务: 应用更改并重启Nginx。
```bash
sudo service nginx restart
```
相关问题与解答
问题1: 如何检查Nginx是否正确启用了Gzip压缩?
答案: 你可以使用浏览器的开发者工具或使用在线工具(如GTMetrix、Google PageSpeed Insights)来检查是否启用了Gzip压缩,这些工具会提供网站资源是否被压缩的信息。
问题2: 如果我想对不同的文件类型设置不同的缓存过期时间,我该如何操作?

答案: 你可以在Nginx配置文件中使用多个location块,每个块针对一种文件类型,并为每种类型指定不同的expires指令。
```nginx
location ~* \.(jpg|jpeg)$ {
expires 7d;
add_header Cache-Control "public, no-transform";
}
location ~* \.(png|gif|ico)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
location ~* \.(css|js)$ {
expires 1y;
add_header Cache-Control "public, no-transform";
}
```
这样,不同类型的文件将有不同的缓存过期时间。