为什么我的 URL 重定向在没有 www 的情况下不起作用?

Why are my URL redirects not working without www?

我想要以下重定向:

http://example.com -> http://www.example.com
example.com -> http://www.example.com
www.example.com -> http://www.example.com

在我的 namecheap 中,我设置了两个 URL 重定向记录:

CNAME Record        | www | appname.us-east-2.elasticbeanstalk.com.
URL Redirect Record |  @  | http://www.example.com                  | Unmasked 

但是,当我实际输入完整的 URL 时,我仍然只能访问 http://www.example.com。当我删除 www 时,请求超时。所以 URL 重定向似乎没有做任何事情。如何正确重定向到我的完整 http 域?

You could make www.domain.com the A record and all the other domainnames CNAMEs of www.domain.com. But this only "solves" that if the IP address of www.domain.com changes you don't have to alter the other DNS enties as they are aliases.

So on the DNS level there is no way to enforce a redirect. And for a good reason because DNS is used for more then only HTTP. For example if all request for domain.com would redirect to www.domain.com your email addresses will change to user@www.domain.com.

因此,对于 HTTP 重定向,您将不得不使用 HTTP 解决方案。这可以在网络服务器级别(nginx、apache 等)

我使用 NGINX 并实现了如下重定向:

vi /etc/nginx/sites-enabled/example-com

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

server {
        listen 80;
        server_name www.example.com;
        root /var/www/html;
        index index.html index.htm;
}

响应状态代码 301 表示 "Moved Permanently" 并用于永久 URL 重定向。

请不要忘记重启 NGINX。

sudo systemctl restart nginx