Enable Expires Headers, gzip compression on nginx
Introduction
Website performance plays an important role in providing a fast and smooth user experience. Static files such as CSS, JavaScript, images, and fonts can increase page load time if they are not properly optimized. Nginx provides built-in features such as Expires headers and Gzip compression that can help reduce bandwidth usage and improve website loading performance.
Prerequisites
- Nginx webserver
- Centos or Ubuntu server
- Installation path:/etc/nginx/
Implementation:
1. Enable Expires headers on Nginx:
Open site configuration file. Let’s assume that, we have only one website on the server and the nginx configuration file “/etc/nginx/sites-enabled/default“, the document root would be /var/www/html.
We are going to add expires header for the following static content files.
ico|css|js|gif|jpe?g|png
vi /etc/nginx/sites-enabled/default
Add the following content under server {
location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
expires 30d;
add_header Pragma public;
add_header Cache-Control “public”;
}
Check the syntax of the nginx configuration
nginx -t
Make sure that there is no error in the configuration.
systemctl restart nginx
Verification:
Execute the following command to verify expires command.
curl -I http://domain.tld/css/assets.min.css
Date: Wed, 28 Dec 2016 05:51:07 GMT
ETag: “585cede3-4d843”
Expires: Fri, 27 Jan 2017 05:51:07 GMT
Last-Modified: Fri, 23 Dec 2016 09:26:59 GMT
Enable gzip compression:
Open nginx configuration file.
vi /etc/nginx/nginx.conf
Enable/Edit/Append the following line on configuration
gzip on;
gzip_disable “msie6”;gzip_vary on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/x-icon image/svg+xml text/js;
Check the nginx configuration
nginx -t
Restart the nginx service.
systemctl restart nginx
Verification:
Execute the following command to verify whether gzip enabled.
curl -I -H "Accept-Encoding: gzip" https://domain.tld/css/asset.min.css
Cache-Control: max-age=2592000
Cache-Control: public
Content-Encoding: gzipConclusion
Enabling Expires headers and Gzip compression in Nginx is a simple and effective way to improve website performance. Expires headers help browsers cache static resources for longer periods, while Gzip compression reduces the size of files transferred between the server and client.
