How to Set Cookie Expiration in NGINX


how to set cookie expiration in nginx

Cookies provide a great way to manage dynamic websites, and track user sessions. They even make it easy to personalize user experience. If you want to terminate user sessions or make them logout, so that you can apply new changes to your website, you can simply set cookie expiry date for each session. Let us take a look at how to set cookie expiration in NGINX.

 

How to Set Cookie Expiration in NGINX

Here are the steps to set cookie expiration in NGINX.

 

1. Open NGINX Config File

Open NGINX config file in a text editor


$ sudo vim /etc/nginx/nginx.conf

 

2. Set Cookie Expiration

You can set the cookie expiration in NGINX with expires directive. If you want to expire all cookies in 1 day, add the following line of code in your server block


server {
expires 1d;
...
}

 

You can add the same directive in a location block too.


location / {
expires 1d; 
...
}

 

If you only want to expire cookies for all URLs in a specific directory (e.g /product/),


location /product/ {
expires 1d;
...
}

 

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

 

Now NGINX will automatically expire user cookies, as per your configuration.

 

 

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!