How exactly does redirect work inside Nginx for non-www and www and what's the "best practice" connect them?

Viewed 39

I have a Virtual Machine with AWS (EC2) with Ubuntu. In this VM, I created a server using Nginx. I have a domain as well from Google Domains, let's call it example.com.

Inside Route 53, which is an AWS product in which you link with DNS to your domain, I generated some Custom Name Servers for example.com and added them inside Google Domains for redirecting purposes. Consequently, I added a type-A connection from example.com to the EC2's IP Address (let's call it 123.45.56.78).

Inside AWS's VM, I added Nginx and edited the file /etc/nginx/sites-available/default

In here, I added the following:

server{
 '''
 server_name example.com www.example.com;
 '''
}

Then, I went to example.com and the default HTML from Nginx showed up. The problem is that I tried to enter www.example.com and the redirect didn't happen.

I tried to add another type A that redirects www.example.com to 123.45.67.89 but nothing happened. Then, I tried to enter a type CNAME that redirects www.example.com to example.com and still nothing.

And some questions came to my mind:

  1. What's the difference between typing inside the sites-available default the following

    server_name example.com www.example.com;

and creating a type A connection between example.com and www.example.com?

  1. What happens if I add both a type A connection from www.example.com to 123.45.67.89 and a type CNAME connection from www.example.com to example.com?

  2. What happens if there's a connection (either type A or CNAME) and server_name is set to example.com www.example.com (just as I added)? Is there a conflict whatsoever?

  3. I figured out that adding this line solved the issues. But is it considered a "good practice"?

    if ($host = 'www.example.com') { return 301 https://example.com$request_uri; }

  4. Also, If I add an SSL to example.com, do I need to add another one for www.example.com? Or is there a better way to handle SSL?

  5. In general, what's the best way to handle www and non-www websites? Should www be redirected to non-www? If yes, should this be done with type A or type CNAME redirects or should they be done inside Nginx? Is there a convention for dealing with suchs redirects? I went all over internet and they seem to have very different solutions for this.

I think a general explanation on how Nginx handles the www and non-www server names and the way they work with or without type A or type CNAMES would solve all of my problems. :)

Softwares' version:

  1. Nginx: 1.18
  2. Ubuntu 20.04
0 Answers
Related