nginx redirects in Docker
Some tips and tricks for configuring nginx in a container.
Using nginx defaults, the directives that return a URL to redirect the client (i.e. rewrite
or return
) will return absolute URLs. In order to keep your docker image portable (and locally testable) you will probably want to configure those using a relative path and let nginx build the absolute URL. Unfortunately, this causes a problem in a container environment since the HTTP port (and possibly scheme) are likely to be translated by Docker on the way down to nginx.
Solution
If you need to specify an absolute URL then you can explicitly construct it using the nginx variables scheme
and http_host
:
server {
listen 80;
server_name foo.com;
# Redirect to www.foo.com, respecting incoming scheme and port
rewrite ^/(.*) "$scheme://www.$http_host/$1" permanent;
}
server {
listen 80;
server_name www.foo.com;
# ...
}
If you do not need absolute URLs then you can sidestep this issue by setting the absolute_redirect
directive to off and using relative URLs:
server {
# ...
absolute_redirect off;
location /foo {
# Redirect to relative URL respecting scheme, host and port
return 302 "/bar";
}
# ...
}