How to Set Cookie with HttpOnly and Secure Flags in Apache


set cookie with httponly and secure flags

Although cookies are used by most website, they pose some security vulnerabilities that allow hackers to launch various types of attacks (such as XSS). You can easily fix these problems by setting HttpOnly and Secure flag in your Apache server. Here’s how to set cookie with HttpOnly and Secure flags in Apache.

 

How to Set Cookie with HttpOnly and Secure Flags in Apache

Here are the steps to set cookie with HttpOnly and Secure flags in Apache server on your website. It basically forces your web server to set cookies the right way.

 

1. Ensure mod_headers is enabled

Apache used mod_headers module to set http response headers. Please ensure that it is installed and activated on your Apache web server. Here are the steps to install & enable mod_headers. You can verify the module with the command


$ sudo apache2ctl -M

This will give you a list of installed modules. You should see mod_headers in it.

 

2. Set Cookie with HttpOnly and Secure Flags

Open your Apache config file in a text editor.

You will find it at one of the following locations, depending on your Linux distribution and type of installation.

  • /etc/apache2/httpd.conf
  • /etc/apache2/apache2.conf
  • /etc/httpd/httpd.conf
  • /etc/httpd/conf/httpd.conf

 


$ sudo vim /etc/apache2/httpd.conf

 

Add the following line Apache config file


Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure

 

If you Apache version < 2.2.4. then add the following line


Header set Set-Cookie HttpOnly;Secure

 

This will ensure that the flags are set even if it isn’t explicitly done in your application.

 

If you want to exclude a specific cookie (e.g SPECIAL-COOKIE) that needs to be used by client side script, then you can exclude it as shown below


Header edit Set-Cookie ^((?!SPECIAL-COOKIE).*)$ $1;HttpOnly;Secure

 

You can even have multiple exceptions if you want, with the help of ‘|’ operator


Header edit Set-Cookie ^((?!SPECIAL-COOKIE|OTHER-COOKIE).*)$ $1;HttpOnly;Secure

 

 

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

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!