Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

docker - Nginx Redirection Issues with multiple domains

So I have two domains:

example.com
example.ca

This is a docker container running nginx and I am trying to accomplish http to https redirect and www to non-www redirect.

Docker on the host is bound to port 80 and 443. To be clear traffic works to and from the server without issue.

The issue is the www redirects seem to be ignored.

When a user goes to http://www.example.com I expect them to be redirected to https://example.com

What happens is they are actually redirected to https://www.example.com

So the https redirection works 100% of the time but for some reason nginx fails to perform the redirect without www

It's worth noting we are using CloudFlare to replace our self signed certificates. So maybe CloudFlare is causing the issue?

Here are my redirects.

    server {
        listen 8080;
        listen 8443;
        server_name www.example.com;
        return 301 https://$host$request_uri?$args;
    }

    server {
        listen 8080;
        listen 8443;
        server_name www.example.ca;
        return 301 https://$host$request_uri?$args;
    }

#   Force http to https
    server {
        listen 8080;
        server_name example.com;
        return 301 https://$host$request_uri?$args;
    }
    
    server {
        listen 8080;
        server_name example.ca;
        return 301 https://$host$request_uri?$args;
    }
question from:https://stackoverflow.com/questions/65923847/nginx-redirection-issues-with-multiple-domains

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can redirect the user from www.example.com to https://example.com usign the page rules from cloudflare. Here is an example: enter image description here

Also you could try withing nginx config Try replacing $host with your domain name so you would have

 server {
        listen 8080;
        server_name www.example.com;
        return 301 https://example.com$request_uri?$args;
    }

Maybe this would do the trick


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...