Create and Configure a New Domain with Nginx

Steps to prepare a new domain with Nginx on Debian-based systems.

Requirements

  • Debian 9 (Stretch)
  • Nginx installed

1. Create the Site Directory

Make a directory structure for the domain.

sudo mkdir -p /var/www/your_domain.com/html

Set the proper ownership and permissions.

sudo chown -R $USER:$USER /var/www/your_domain.com/html
sudo chmod -R 755 /var/www/your_domain.com

Create the index.html file.

nano /var/www/your_domain.com/html/index.html

index.html

<html>
  <head>
    <title>Welcome to your_domain.com!</title>
  </head>
  <body>
    <h1>Success! The your_domain.com server block is working!</h1>
  </body>
</html>

2. Configure Nginx

Create the site configuration file.

sudo nano /etc/nginx/sites-available/your_domain.com

your_domain.com

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

    root /var/www/your_domain.com/html;
    index index.html index.htm index.nginx-debian.html;

    server_name your_domain.com www.your_domain.com;

    location / {
        try_files $uri $uri/ =404;
    }
}

Enable the site with a symbolic link.

sudo ln -s /etc/nginx/sites-available/your_domain.com /etc/nginx/sites-enabled/

Prevent hash bucket size issues with long domain names.

sudo nano /etc/nginx/nginx.conf

Press CTRL + W, search for server_names, press Enter, and uncomment the line.

nginx.conf

http {
    ...
    # server_tokens off;

    server_names_hash_bucket_size 64;
    # server_name_in_redirect off;
    ...
}

Save with CTRL + O, confirm with Enter, and exit with CTRL + X.

Validate the syntax.

sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Reload Nginx.

sudo systemctl restart nginx

3. Local Domain Mapping (Optional)

Add the domain to the host file if you want to test it locally.

sudo nano /etc/hosts

hosts

127.0.0.1       localhost
127.0.1.1       debian

127.0.0.1       your_domain.com

4. Verification

Visit http://your_domain.com in the browser or run:

curl http://your_domain.com
<html>
  <head>
    <title>Welcome to your_domain.com!</title>
  </head>
  <body>
    <h1>Success! The your_domain.com server block is working!</h1>
  </body>
</html>

References

Published: June 6, 2020