X-Forwarded-Proto https in frontend or backend (HAProxy)?
Asked Answered
A

1

14

I have setup a HAProxy in front of my backend server application to enable HTTPS. I have read that I need to set X-Forward-Proto https.

In the haproxy.cfg file I have tried to do that in the frontend with:

frontend haproxy
  bind :8443 ssl crt frontend/server.pem
  reqadd X-Forwarded-Proto:\ https
  default_backend my-backend

and that seems to make it work - e.g. I can both login to my backend server and navigate to the different pages. If I DON'T have the proto option I can only login but not navigate to any other pages.

Now I if add the option in the backend instead (removing it from the front end) with:

backend my-backend
  http-request add-header X-Forwarded-Proto https if { ssl_fc }
  server my-backend 127.0.0.1:9000

it also works, I can navigate the different pages in my backend server application.

So which is the correct way to do it? In the frontend or in the backend or does it not matter?

Alisander answered 20/8, 2018 at 10:12 Comment(0)
G
24

It doesn't matter. When you have multiple backends, it usually makes sense to do this on the frontend.

You could also use http-request set-header X-Forwarded-Proto in the front-end, rather than using reqadd.

The req* directives are much older functionality than http-request so the latter is preferred, generally, but there's an important reason why you should prefer it, here and why you should be using set-header instead of add-header: you don't want the client to be able to forge headers that only the proxy should be injecting. For non-https front-ends, you should also http-request set-header X-Forwarded-Proto http so that there is no possibility of an incorrect upstream header. The add-header option, just like reqadd, does not remove any existing headers of the same name, while set-header does.

Goggin answered 21/8, 2018 at 0:32 Comment(4)
Ok so in the frontend do you mean that I should set "http-request set-header X-Forwarded-Proto https if { ssl_fc }" or "http-request set-header X-Forwarded-Proto:\ https"? Not sure the last version is correctly formatted/correct.Alisander
http-request set-header X-Forwarded-Proto https. The colon and backslash are not used.Goggin
also note http-request set-header X-Forwarded-Port <port_number> can be used to forward to a non-standard portEckmann
@CorinFletcher I have only ever seen X-Forwarded-Port: <int> used on the front-end to notify the back-end which port the request arrived on at the front-end, rather than where it's being forwarded to. An HTTP request arriving at the front-end as HTTP on port 8080 would (e.g.) contain X-Forwarded-Proto: http and X-Forwarded-Port: 8080 so that the back-end can have sufficient information to rebuild the URL ${x-forwarded-proto}://example.com:${x-forwarded-port}/, in cases where that's needed. In HAProxy, this would be http-request set-header X-Forwarded-Port %fp.Goggin

© 2022 - 2024 — McMap. All rights reserved.