[Solved] Adding header to response if it does not exist yet
Added by kangaroo over 5 years ago
Hi
I have a configuration where lighttpd is serving some sites ("vHosts") and (reverse) proxying others. I would like to set for example an
X-Frame-Options: SAMEORIGIN
header for all pages lighttpd serves.
I have done this along the line of the following idea
$SERVER["socket"] == "0.0.0.0:443" { ... setenv.add-response-header += ( "X-Frame-Options" => "SAMEORIGIN", )
which is working/doing the right thing if there is NO "X-Frame-Options" header in the response.
However, if there already is such a header (which seems to be the case for a proxied application for example), I end up with a duplicate header in the response. And if the application sets a different value for the header, the resulting response has them both.
So I tried using "setenv.set-response-header" ("set" instead of "add") which eliminates the duplicate but overrides the header value the application set "earlier". So if the app for example sets "X-Frame-Options: DENY", I still see a "X-Frame-Options: SAMEORIGIN" in the final response.
Is there a way to have lighttpd only set a header if it is not present? Or is there a better way to achieve my goal?
I am running lighttpd 1.4.54 on FreeBSD 12.1.
Replies (2)
RE: Adding header to response if it does not exist yet - Added by gstrauss over 5 years ago
As you have noted setenv.add-response-header
adds (or appends), and setenv.set-response-header
sets (overrides) a header.
Is there a way to have lighttpd only set a header if it is not present? Or is there a better way to achieve my goal?
If your do not want lighttpd to add the header for requests served by the backend, then create a condition in the lighttpd config for things that are sent to the backend, and then create an "else" clause which has setenv.set-response-header to set the header (on those requests which did not get sent to the backend)
RE: Adding header to response if it does not exist yet - Added by kangaroo over 5 years ago
Thank you for this input. It turns out that it is exactly what I need: as I am forwarding complete subdomain(s) to the backends it is pretty straight forward to implement the if/else
.
$SERVER["socket"] == "0.0.0.0:443" { ... $HTTP["host"] !~ "^sub.example.com$" { setenv.set-response-header += ( "X-Frame-Options" => "SAMEORIGIN", "Strict-Transport-Security" => "max-age=15552000; includeSubDomains; preload", ) } else { setenv.set-response-header += ( "Strict-Transport-Security" => "max-age=15552000; includeSubDomains; preload", ) } ... }