haproxy: intercept all cookies and set secure attribute

01-02-2014 | Remy van Elst

Table of Contents

This snippet shows you how to use haproxy to set the secure attribute on cookies. You might have a backend application which is not able to set the secure attribute on cookies or for which haproxy does the ssl offloading. This simple frontend rspirep sets the secure attribute for all cookies.

If you like this article, consider sponsoring me by trying out a Digital Ocean VPS. With this link you'll get a $5 VPS for 2 months free (as in, you get $10 credit). (referral link)

Add the following to a frontend block:

rspirep ^(set-cookie:.*)  \1;\ Secure

Like so:

frontend example-frontend
  reqadd X-Forwarded-Proto:\ https
  rspadd Strict-Transport-Security:\ max-age=31536000;\ includeSubDomains
  option forwardfor except
  maxconn 2000
  rspirep ^(set-cookie:.*)  \1;\ Secure
  default_backend example-backend

This will set (and re-set) all your cookies with the secure attribute on.

Documentation on rspirep

Tags: cookies  haproxy  loadbalancer  secure  ssl  tutorials