首页 > 解决方案 > 多个域的 Nginx 重定向问题

问题描述

所以我有两个域:

example.com
example.ca

这是一个运行 nginx 的 docker 容器,我正在尝试完成 http 到 https 的重定向和 www 到非 www 的重定向。

主机上的 Docker 绑定到端口 80 和 443。要明确的是,进出服务器的流量可以正常工作。

问题是 www 重定向似乎被忽略了。

当用户访问http://www.example.com我希望他们被重定向到https://example.com

发生的情况是它们实际上被重定向到https://www.example.com

因此,https 重定向 100% 的时间都有效,但由于某种原因,nginx 无法在没有 www 的情况下执行重定向

值得注意的是,我们正在使用 CloudFlare 来替换我们的自签名证书。那么也许是 CloudFlare 导致了这个问题?

这是我的重定向。

    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;
    }

标签: dockernginxdocker-composenginx-config

解决方案


您可以使用来自 cloudflare 的页面规则将用户从www.example.com重定向到https://example.com 。这是一个例子: 在此处输入图像描述

您也可以尝试使用 nginx 配置尝试将 $host 替换为您的域名,这样您就可以

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

也许这可以解决问题


推荐阅读