CNAME in Route 53 – Redirect www to non-www not working

amazon-route53cname-recorddomain-name-system

I'm hosting web application on AWS with Nginx 1.6.3 and django 1.7.6

I'd like to redirect www.mydomain.com to mydomain.com through Route 53

In other words, showing mydomain.com/foo on address bar when user typed www.mydomain.com/foo


Route 53 Configuration

mydomain.com

  • Type : A record
  • Value : ALIAS {Elastic Load Balancer A record}

www.mydomain.com

  • Type : CNAME
  • Value : mydomain.com

With above configuration, mydomain.com is well working but www.mydomain.com returns 400 Bad request error. Of course, I've tried it on secret mode(cache-free) with enough time interval(more than 24 hrs). Adding http:// at front returns same error.


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

If I added above code at nginx.conf, www.mydomain.com redirected to mydomain.com as I expected. However, I'm not sure that editing web server configuration is necessary to use CNAME service. How can I use CNAME service without editing web server?

Best Answer

This sounds like expected behavior. Exactly what happens when the HTTP server receives a request that it does not know how to deal with can differ, but no redirect is expected unless it happens at the HTTP level.

A CNAME record is merely stating that a given name in DNS is an alias of a different name in DNS.

What happens when you have a CNAME record in place is that when your HTTP client makes an A or AAAA query for the alias name they will get the IP address associated with the actual name returned.

They will then connect to that address, knowing it is the address associated with the name they looked up (the alias) and make an entirely normal request.

When you have name-based virtual hosts, what the HTTP server cares about is what the Host header says and the client will put whatever hostname that was in the URL it navigated to as the value of that header (in this example, the alias).

If you want to redirect an HTTP client you need an HTTP redirect, like that in your own example.