Nginx – How to Redirect Domain Root to CloudFront

amazon-cloudfrontamazon-web-servicesdomain-namenginx

Note – I see several other questions asking about redirecting to the root of their S3 static websites, but I didn't see anything about redirecting from the root of a domain name to a CloudFront/S3 site.

I have my personal website deployed to AWS CloudFront & statically hosted on S3. I have a www. CNAME record pointing to the CloudFront hostname, and that works properly, but I've discovered that you can't have a CNAME record for the domain root. I already have a VPS with nginx that's hosting several of my other projects – is it fine to simply add an A record from the domain root to my VPS IP, and have nginx redirect requests for the domain root to the CloudFront hostname?

Edit: to clarify – what I would like to happen is for all traffic heading to example.com be forwarded to the CloudFront hostname assigned to my website. I am able to do this with www.example.com by creating a CNAME record for 'www.' pointing to the desired hostname. However, it appears that Google Domains does not allow CNAME records to be created for the root (i.e. just example.com), and so I am wondering how to forward traffic from example.com to my CloudFront hostname (as opposed to what I can do right now, which is only to forward www.example.com to cloudfront).

And in case it's relevant, I can't do any sort of wildcard redirect because I am using other hostnames on the domain for different projects that require specific A records.

And would this be an acceptable/good practice nginx configuration for the site? I think it would work because www.example.com is already properly forwarding to the CloudFront hostname.

server {
        listen 443 ssl;
        server_name example.com;
        rewrite ^/$ https://www.example.com permanent;
        ssl_certificate           /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key       /etc/letsencrypt/live/example.com/privkey.pem;
}

Best Answer

By domain root, I assume you mean example.com, instead of www.example.com, and that you want to point that to your AWS cloud web app. One thing you can do is create an A record named @, which essentially says "this is me. Any DNS requests to me (example.com) should go to this IP address." Then add a CNAME www that points to @. You can use Nginx if you want, Nginx used for pass-through is just a reverse proxy. It will act as a middle man of any requests between the client and the server. Nginx just repeats those messages between the client and the server.

I hope that was any help, my feeling is I read the question wrong

Related Topic