Friday, January 2, 2015

Setting Up Multiple Domains on Nginx

I moved two domains off my shared hosting server to my Digital Ocean account.

It's a three-step process:

  • Point the domains to new name servers
  • Add domains to DNS
  • Writing Nginx configuation files

Use the domain registrar's control panel to change the domain name server addresses. I pointed both domains to the Digital Ocean name servers.

Before creating new configuration files for Nginx, create directories and index.html files for each of the domains. The server needs something to serve and Nginx needs a path to the root of each server defined in a server block.

On Digital Ocean, there's a control panel for my Droplet that let's me associate a domain name with a server IP address. I add both of my domain names and point them at the IP address for my Droplet.

This is a server block:

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /usr/share/nginx/html/myDomainName.com/public_html/;
        index index.html index.htm;

        server_name myDomainName.com www.myDomainName.com;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }
}

The first two lines tell Nginx which port to listen for request. The first is for IPv4 and the second is for IPv6.

Next, tell Nginx where to find the root of the web server. The path that follows points to the index.html file. the next line, index index.html index.htm, tells Nginx what file name to look for.

server_name is a parameter that accompanies a server request. Only if the server name matches myDomainName.com or www.myDomainName.com, Nginx looks in the root for an index.html file and returns it.

The location block inside the server block contains a try_files directive. This tells Nginx how to handle the situation if there's no index.html file at the root location. In this case, it tells Nginx to return a 404 error.

Notice that default_server is red and in bold. It's trying to say that only one server block can have the string default_server in the listen statement. I could configure twenty domains on my DO Droplet, but only one can have default_server in the listen statement.


Sources:
Nginx Documentation - Server Names
Multiple Nginx Server Blocks
Set up a Host Name on Digital Ocean Droplet

No comments:

Post a Comment