How to Set Cookie with HttpOnly and Secure Flags in NGINX


set httponly and secure flags nginx

Website cookies, if not set properly, can pose security vulnerabilities exploited by hackers. You can fix them easily with the help of HttpOnly and Secure flags in your NGINX server. Here’s how to set cookie with HttpOnly and Secure flags in NGINX.

 

How to Set Cookie with HttpOnly and Secure Flags in NGINX

Here are the steps to set cookie with HttpOnly and Secure flags in NGINX.

 

1. Open NGINX Config file

Open NGINX config file in a text editor. You will generally find it at /etc/nginx/nginx.conf


$ sudo vim /etc/nginx/nginx.conf

 

2. Set cookie with HttpOnly and Secure

There are 2 ways to set HttpOnly and Secure flags in cookies.

 

Using nginx_cookie_flag_module Module

nginx_cookie_flag module allows you to set cookie flag as HttpOnly and Secure in Set-Cookie response header.

To enable it, you need to build NGINX using this module, during installation, by adding the following option.


--add-module=/path/to/nginx_cookie_flag_module

 

Once you have built NGINX with the above module, you can simply add the following line in your NGINX config file.


set_cookie_flag HttpOnly secure;

 

Using proxy_cookie_path

Alternatively, you can also add the following line your ssl.conf or default.conf file


proxy_cookie_path / "/; HTTPOnly; Secure";

 

3. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload

 

4. Testing

You can use one of the HTTP response header tools to enter your website URL and examine the headers.

 

 

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!