How to Set Last Modified Date Header in NGINX


set the last modified header in nginx

Caching not only improves website speed but also reduces server load and data bandwidth. Last Modified Date header is an important HTTP header that is responsible for caching your website. Web browsers use it to determine if they need to request your server for a fresh copy of your page. Let’s take a look at how to set last modified date header for your website.

Please note, it is not advisable to remove or delete Last Modified Date for your website. It might mess up caching completely.

 

How to Set Last Modified Date Header in NGINX

Here are the steps to set last modified date header in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

 


$ sudo vim /etc/nginx/nginx.conf

 

2. Set Last Modified Date Header

You can set any response header in NGINX with the add_header directive. Just add it to your location block


location / {
add_header Last-Modified "Sun Feb 1 00:32:50 EDT 2019";
...
}

 

The above code will set last modified date to a fixed value. If you want the last modified date to be something dynamic, you can use one of the server variables


location / {
add_header Last-Modified $date_gmt;
...
}

 

If you want to set last modified date only for a specific URL then add the add_header directive only for that URL’s location block.


location /path-to-url/ {
add_header Last-Modified "Sun Feb 1 00:32:50 EDT 2019";
...
}

 

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

That’s it! NGINX will automatically set last modified date for your website, as per your specifications. However, be careful while setting last modified date header. If you don’t set it properly, it might invalidate the cache of all your users and trigger a flood of requests for fresh content.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!