How to set Secure attribute to Set-cookie in Nginx through nginx.conf file

RamRajVasavi picture RamRajVasavi · Feb 20, 2018 · Viewed 22.6k times · Source

I am new to Nginx server. recently started working nginx project. I have task to set security headers through nginx.conf file. I set some header correctly but not able to set for Set-cookie. My requirement is, in response header Set-Cookie should have Secure and HTTPOnly attributes. Added below two directives in nginx.conf file

set_cookie_flag HttpOnly Secure;
proxy_cookie_path / "/; HTTPOnly; Secure";

Tried with each one and both also, but only HttpOnly coming. Please look into below for my conf file snippet

server {
    listen       80;
    server_tokens off;
    server_name  http://{{ getenv "PROXY_URL" }};
    set_cookie_flag HttpOnly Secure;
    proxy_cookie_path / "/; HTTPOnly; Secure"; 
    include routes;     
}

Please help me, what I need to add here or anything I missed.

Thanks in Advance.

Answer

Amirhossein Farmad picture Amirhossein Farmad · Jun 9, 2019

Another alternative option is to:

  1. Go to this directory: "/etc/nginx/conf.d".

  2. Create an empty text file by the name of ssl.conf (As you see There is example_ssl.conf there).

  3. Add the below syntax in ssl.conf (or default.conf):

    server { proxy_cookie_path / "/; HTTPOnly; Secure";}

    note that the whole path "/" will be replaced. For example the directive "proxy_cookie_path /two/ /;" will rewrite “path=/two/one/uri/” to “path=/one/uri/”.

  4. Open /etc/nginx/nginx.conf and add following command:

    include /etc/nginx/conf.d/ssl.conf

  5. Restart the Nginx to see the results.