Redirect from http non-www to https www (single redirect)
See original GitHub issueHi guys,
I’m trying to redirect http://example.com with a single 301 redirect to https://www.example.com.
While a redirect is easily achieved with some nginx configuration, here’s the problem with the nginx-proxy:
The problem When SSL is enabled (letsencrypt companion) and the non-www alias is added to the VIRTUAL_HOST and LETSENCRYPT_HOST env’s, the nginx proxy automatically creates a server block to redirect from http to https, like this:
server {
server_name example.com;
listen 80 ;
access_log /var/log/nginx/access.log vhost;
return 301 https://$host$request_uri;
}
So http://example.com will 301 redirect to https://example.com.
While this is neat, my website must redirect to https://www.example.com instead.
Options? I can ofcourse create a redirect in my own proxied webcontainer, that will redirect non-www requests to www, like this:
server {
listen 80;
listen 443 ssl;
server_name example.com;
rewrite ^(.*) https://www.example.com$1 permanent;
}
The problem is though, this will result in a double 301 redirect:
- http://example.com -> https://example.com (redirect by nginx-proxy)
- https://example.com -> https://www.example.com (redirect by my own webcontainer)
I want to have a single redirect (for SEO purposes)
The second thing I’ve tried is adding rewrite ^(.*) https://www.example.com$1 permanent;
to /etc/nginx/vhost.d/example.com
in the nginx-proxy. This will add the configuration to the “listen 443” block only, and this won’t do anything because the http to https from the nginx-proxy will still come first.
Any idea how I can fix this with a single redirect from http:// to https://www…?
Thanks in advance
Issue Analytics
- State:
- Created 5 years ago
- Comments:23 (2 by maintainers)
It seems many of the solutions above “work” but end up using multiple redirects, which is specifically what the OP is trying to avoid.
I finally got this working with a single redirect with the following incantation:
The piece that was missing from most other solutions in this (and other) threads was
HTTPS_METHOD: noredirect
which disables the first redirect bynginx-proxy
and allows the container (in this casecusspvz/redirect
) to do a single redirect.In case it helps anyone, I created https://github.com/adamkdean/redirect to make this easier.