In order for Sinatra to correctly assemble the url used for redirects, it needs to be able to determine whether the request is using ssl, so that the redirect can be made using http
or https
as appropriate.
Obviously the actual call to thin isn't using ssl, as this is being handled by the front end web server, and the proxied request is in the clear. We therefore need a way to tell Sinatra that it should treat the request as secure, even though it isn't actually using ssl.
Ultimately the code that determines whether the request should be treated as secure is in the Rack::Request#ssl?
and Rack::Request#scheme
methods. The scheme
methods examines the env
hash to see if one of a number of entries are present. One of these is HTTP_X_FORWARDED_PROTO
which corresponds to the X-Forwarded-Proto
HTTP header. If this is set, then the value is used as the protocol scheme (http
or https
).
So if we add this HTTP header to the request when it is proxied from nginx to the back end, Sinatra will be able to correctly determine when to redirect to https
. In nginx we can add headers to proxied requests with proxy_set_header
, and the scheme is available in the $scheme
variable.
So adding the line
proxy_set_header X-Forwarded-Proto $scheme;
to the nginx configuration after the proxy_pass
line should make it work.
proxy_set_header X-Forwarded-Proto $scheme;
after yourproxy_pass
line help? – Wheelbarrow