How to Delete Cookie in NGINX


delete cookie in nginx

Cookies allow you to track user sessions and personalize user experience. However, if they start giving errors or causing issues, then it might be a good idea to simply remove them. Let us take a look at how to delete cookie in NGINX.

 

How to Delete Cookie in NGINX

Here are the steps to delete cookie in NGINX.

 

1. Open NGINX Config File

Open NGINX config file in a text editor


$ sudo vim /etc/nginx/nginx.conf

 

2. Delete Cookie

Add the following code to delete a cookie named ‘some_cookie’

set $new_cookie $http_cookie;
if ($http_cookie ~ "(.*)(?:^|;)\s*some_cookie=[^;]+(.*)") {
    set $new_cookie $1$2;
}
proxy_set_header Cookie $new_cookie;

 

You can also expire cookies using the expires directive

location ~* ^.+\.(css|js|jpg|gif|png|txt|ico|swf|xml)$ {
root /usr/local/nginx/htdocs;
expires 0d;
}
OR add_header directive
location ~* ^.+\.(css|js|jpg|gif|png|txt|ico|swf|xml)$ {
root /usr/local/nginx/htdocs;
add_header Set-Cookie "value=1;Domain=.example.com;Path=/;Max-Age=0";
}
The above code will expire the cookies for css, js, jpg, gif, png, txt, ico, swf, and xml files.

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 delete or expire 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!