This is a data compression technique before sending, helping to reduce bandwidth and increase data transmission speed.
To implement the Compress Responses feature, we will use the gzip and gzip_comp_level directives, please refer to the following example
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /env/nginx/mime.types;
gzip on;
gzip_comp_level 3;
gzip_types text/css text/javascript;
server {
listen 80;
server_name nglearns.test;
root /srv/nglearns/static-demo;
location ~* \.(css|js|jpg)$ {
access_log off;
add_header Cache-Control public;
add_header Pragma public;
add_header Vary Accept-Encoding;
expires 1M;
}
}
}
Here, we can see that by using the gzip directive with the value on, we can easily enable the data compression feature.
In addition, with the gzip_comp_level directive, we can easily determine the content compression level of nginx
Next is the gzip_types directive, with this attribute, we will tell nginx which file types need to be compressed, in this case, it is css and js with the settings text/css and text/javascript
Finally, don't forget to use the add_header Vary Accept-Encoding; directive. With this attribute, we will tell the client that the response content will depend on the content that the client accepts.
Please test through the following query
curl -I http://nglearns.test/mini.min.css
Result
# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Sun, 25 Apr 2021 16:30:32 GMT
# Content-Type: text/css
# Content-Length: 46887
# Last-Modified: Sun, 25 Apr 2021 08:35:33 GMT
# Connection: keep-alive
# ETag: "608529d5-b727"
# Expires: Tue, 25 May 2021 16:30:32 GMT
# Cache-Control: max-age=2592000
# Cache-Control: public
# Pragma: public
# Vary: Accept-Encoding
# Accept-Ranges: bytes
Here, you can see that no data is compressed. So let's try with the following query
curl -I -H "Accept-Encoding: gzip" http://nglearns.test/mini.min.css
Result
# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Sun, 25 Apr 2021 16:31:38 GMT
# Content-Type: text/css
# Last-Modified: Sun, 25 Apr 2021 08:35:33 GMT
# Connection: keep-alive
# ETag: W/"608529d5-b727"
# Expires: Tue, 25 May 2021 16:31:38 GMT
# Cache-Control: max-age=2592000
# Cache-Control: public
# Pragma: public
# Vary: Accept-Encoding
# Content-Encoding: gzip
As you can see, the data has been compressed through the Content-Encoding information with the value gzip, and of course, the data of the file that has been compressed will be much smaller than the normal file.