nginx 配置 gzip 压缩

配置 nginx

创建 gzip 通用配置

创建一个用于保存 nginx 通用配置的目录:

sudo mkdir -p /etc/nginx/common

新建 gzip 通用配置文件:

sudo vim /etc/nginx/common/gzip.conf

插入配置:

# gzip.conf

# on | off
gzip on;

# compression level (1 - 9, 6 is supported)
gzip_comp_level 6;

# minimum length of a response ("Content-Length" response header)
gzip_min_length 1k;

# buffers size
gzip_buffers 16 8k;

# minimum HTTP version
gzip_http_version 1.1;

# disables on IE6 (matching "User-Agent" request header)
gzip_disable "MSIE [1-6]\.";

# inserting the “Vary: Accept-Encoding” response header
gzip_vary on;

# pre-compress static files
gzip_static on;

# enables compression for all proxied requests
gzip_proxied any;

# enables compression for the specified MIME types
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

常见的图片格式(如 JPEG、PNG、GIF、WebP)本身已经是压缩后的二进制文件,再次用 gzip 压缩效果有限(通常低于 5%),但会增加服务器 CPU 开销,一般不对图片开启 gzip 压缩。

网站引入 gzip 配置

打开需要开启 gzip 的网站配置文件:

sudo vim /etc/nginx/sites-available/avinzheng.com.conf

server 域里引入 gzip 通用配置文件:

server {
  listen 80;
  server_name avinzheng.com;
  root /home/wwwroot/avinzheng.com;
  index index.html;
  ...

  # gzip
  include /etc/nginx/common/gzip.conf;
}

重启 nginx 服务

验证 nginx 配置是否正确:

sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

重启 nginx 服务:

sudo systemctl restart nginx

参考文献