Intermediate · 12 min · practise every command in the built-in terminal

Configuration & Server Blocks

One nginx can serve many websites. Each one is a server block: which port it listens on, which names it answers to, and where its files are.

cat /etc/nginx/nginx.conf

The main file includes the sites at the end:

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

A second site

First its files:

sudo mkdir -p /var/www/shop
echo '<h1>Welcome to the shop</h1>' | sudo tee /var/www/shop/index.html

Then its server block in sites-available (write it with sudo nano /etc/nginx/sites-available/shop):

server {
    listen 80;
    server_name shop.local;
    root /var/www/shop;
    index index.html;
}
DirectiveMeaning
listen 80;the port
server_name shop.local;the name(s) this site answers to
root /var/www/shop;its files
location /path { … }special rules for part of the site

Switch it on

A site is on when sites-enabled has a link to it:

sudo ln -s /etc/nginx/sites-available/shop /etc/nginx/sites-enabled/
ls -l /etc/nginx/sites-enabled

To switch it off again, remove the link (sudo rm /etc/nginx/sites-enabled/shop) — the file in sites-available stays.

Test, then reload

sudo nginx -t                  # check every file for mistakes
sudo systemctl reload nginx    # read the configuration again

nginx reads its configuration when it starts or reloads — until then it keeps serving the old one. Always run nginx -t first: a reload with a broken file fails, and a restart with one takes the whole web server down.

Ask for the right site

Both sites listen on port 80; nginx picks one by the name in the request (the Host header):

curl localhost                          # the default site
curl -H 'Host: shop.local' localhost    # the shop

Or teach this machine the name and use it like a real address:

echo '127.0.0.1 shop.local' | sudo tee -a /etc/hosts
curl shop.local

Practice tasks

  1. Create the shop's page /var/www/shop/index.html saying Welcome to the shop
  2. Write the shop's server block in /etc/nginx/sites-available/shop (server_name shop.local, root /var/www/shop)
  3. Switch the site on with a link in sites-enabled
  4. Test the configuration, then reload nginx
  5. Get the shop's page by its name

Commands in this lesson

Web Server (nginx)