HAProxy Insert Security Response Headers

How to insert common HTTP security related headers into server responses using HAProxy

It’s up to you to decide if these are worthwhile.

Adding Headers Unconditionally

These will add the headers regardless of whether they are already present or not. This can result in duplicate headers in a single response. I’ve not found this is a problem but it’s certainly sub-optimal.

Valid in the listen, frontend or, probably most appropriately, backend sections.

backend some_name
  http-response add-header X-Frame-Options:\ SAMEORIGIN # Or DENY
  http-response add-header X-XSS-Protection:\ 1;\ mode=block
  http-response add-header X-Content-Type-Options:\ nosniff
  http-response add-header Strict-Transport-Security max-age=31536000;\ includeSubDomains;\ preload
  http-response add-header Referrer-Policy no-referrer

Adding Headers Conditionally

To avoid duplicate headers, use some ACLs to check for their existence.

Valid in the listen, frontend or, probably most appropriately, backend sections.

backend some_name
  acl xfo_exists res.hdr_cnt(X-Frame-Options) gt 0
  acl xxp_exists res.hdr_cnt(X-XSS-Protection) gt 0
  acl xcto_exists res.hdr_cnt(X-Content-Type-Options) gt 0
  acl hsts_exists res.hdr_cnt(Strict-Transport-Security) gt 0
  acl rp_exists res.hdr_cnt(Referrer-Policy) gt 0
  http-response add-header X-Frame-Options SAMEORIGIN if ! xfo_exists
  http-response add-header X-XSS-Protection 1;\ mode=block if ! xxp_exists
  http-response add-header X-Content-Type-Options nosniff if ! xcto_exists
  http-response add-header Strict-Transport-Security max-age=31536000;\ includeSubDomains;\ preload if ! hsts_exists
  http-response add-header Referrer-Policy no-referrer if rp_exists