Additional menu

How to Implement HTTPOnly and Secure Cookie in Nginx?

How to Implement HTTPOnly and Secure Cookie in Nginx?

One of you asked this.

I love feedback! It gives me an idea of what to write.

Previously, I explained how to configure Apache HTTP server with HTTPOnly and Secure flag and in this article, I’ll talk about doing the same thing on Nginx web server.

Having HTTPOnly and Secure in HTTP response header can help to protect your web applications from cross-site scripting and session manipulation attacks.

There are multiple ways to get this configured.

  • Within application code by developers
  • Injecting headers from network edge, F5
  • Configuring at web servers

There are two possible ways to achieve this in Nginx web server.

By using “nginx_cookie_flag_module” Module

A Nginx module called nginx_cookie_flag by Anton Saraykin let you quickly set cookie flag as HTTPOnly and Secure in Set-Cookie HTTP response header.

One thing you got to keep in mind that you need to build Nginx from the source code by adding the module.

Ex:

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

Once Nginx is built with the above module, you can add the following line either in location or server directive in respective configuration file

set_cookie_flag HttpOnly secure;

Restart Nginx to verify the results

By using proxy_cookie_path

Another alternative option is to add the below syntax in ssl.conf or default.conf

proxy_cookie_path / "/; HTTPOnly; Secure";

Restart the Nginx to see the results

Verification

If you are testing Intranet based sites, then you can use “Developer Tools” in Chrome to examine the request headers. However, for Internet-facing, you can use online HTTP response header checker tool.

I hope this helps to secure & harden Nginx web server.

Reader Interactions

Chandan Kumar
About Chandan
Chandan Kumar is the founder and editor of Geek Flare. Learn more here and connect with him on Twitter.

Comments

      • Hi Chandan,
        Added this module to my nginx and rebuild in linux OS. In nginx.conf file added below lines of code
        server {
        listen 80;
        server_tokens off;
        server_name http://{{ getenv “PROXY_URL” }};
        set_cookie_flag HttpOnly Secure;
        proxy_cookie_path / “/; HTTPOnly; Secure”;
        include routes;
        }

        but for Set-Cookie, not getting Secure attribute. Under response cookie also HTTPOnly and Secure has un ticked.
        Please help me on this

  1. The second way isn’t well because blindly adds the items. For example, we use the following option:
    proxy_cookie_path / “/; secure”;
    Let’s assume that upstream already sets the secure flag:
    Set-Cookie: foo=bar; path=/; secure
    In this case Nginx will duplicate it as follows:
    Set-Cookie: foo=bar; path=/; secure secure

Leave a Reply

Your email address will not be published. Required fields are marked *