Chapter 8 · Lesson 1 of 8
Web servers and proxies

Nginx from scratch on Ubuntu: install, server blocks, reload

Nginx is a web server that reads its rules from config files, so you install it, describe a site in a server block, test the syntax and reload it.

By the end you will

Install nginx, serve a static site from its own server block and reload it safely after testing the config.

Time
20 min
Level
Beginner
Check
4 questions
You need
  • An Ubuntu server you can reach over SSH with sudo
  • Port 80 open in the firewall

Nginx serves files and forwards requests, and everything it does comes from text files you write. On Ubuntu the pattern is: install the package, put one file per site in sites-available, link it into sites-enabled, test it, then reload. This lesson builds a static site that way and shows where to look when it does not behave.

How it works#

The nginx package starts a master process that reads /etc/nginx/nginx.conf and runs worker processes that handle requests. That main file ends with include /etc/nginx/sites-enabled/*;, so every file linked in that folder is part of the config.

Each site is one or more server blocks. A server block says which port to listen on (listen), which host names it answers to (server_name), and what to do with a request (root, index, location). When a request arrives, nginx first picks the server block by port and by the Host header, then picks a location inside it.

Nginx runs as a systemd service. A reload (systemctl reload nginx) sends a signal so new workers start with the new config while old workers finish their requests. If the new config is broken, nginx keeps the old one. That is why you run nginx -t first and reload instead of restart.

Step 1: Install nginx#

bash
sudo apt update
sudo apt install nginx

The package enables and starts the service. Check it:

bash
systemctl status nginx --no-pager
curl -I http://localhost

What you should see: active (running) and a 200 OK with Server: nginx. The page at http://203.0.113.10 shows “Welcome to nginx” if port 80 is open. If it does not load from outside, see set up a firewall with ufw.

Step 2: Create the site content#

bash
sudo mkdir -p /var/www/example.com/html
echo '<h1>Hello from example.com</h1>' | sudo tee /var/www/example.com/html/index.html

Nginx workers run as the www-data user on Ubuntu, so the files must be readable by it. Files you create with the default umask are world readable, which is enough. See Linux file permissions if you get a 403 later.

Step 3: Write the server block#

Create /etc/nginx/sites-available/example.com:

nginx
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    root /var/www/example.com/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}
  • listen 80 and listen [::]:80 accept IPv4 and IPv6.
  • server_name lists the host names this block answers to.
  • root is the folder that maps to the URL /. A request for /about.html reads /var/www/example.com/html/about.html.
  • index names the file served for a directory URL.
  • try_files checks the exact file, then a directory with an index, then returns 404. A single page app would end with /index.html instead of =404.

Step 4: Enable the site and test#

bash
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t

What you should see: syntax is ok and test is successful. If it names a file and line, fix that line first. Do not reload on a failed test.

Step 5: Make it the default and reload#

The stock default file in sites-enabled has default_server on port 80, so requests with an unknown host name land there. You have two choices. Remove the link (sudo rm /etc/nginx/sites-enabled/default, the original stays in sites-available), or mark your block instead:

nginx
listen 80 default_server;

Only one block per port may be default_server, or nginx -t fails with a duplicate error. Then apply it:

bash
sudo systemctl reload nginx

Check it worked#

bash
curl -I http://example.com
curl -s http://example.com
sudo tail -n 5 /var/log/nginx/access.log

The headers show 200 OK, the body shows your heading, and the access log shows the requests. Before DNS exists you can test with curl -H 'Host: example.com' http://203.0.113.10. Details on log reading are in read logs with journalctl, and the nginx-specific files are /var/log/nginx/access.log and /var/log/nginx/error.log.

Edge cases and gotchas#

  • A symlink needs an absolute path. ln -s sites-available/example.com sites-enabled/ creates a broken link, because the link is resolved from its own folder. Use the full /etc/nginx/sites-available/... path.
  • A missing semicolon breaks the whole file. Every directive ends with ;. The error names the line after the real mistake, so look one line up.
  • root inside location repeats work. Put root at server level so every location shares it, and override only where needed.
  • nginx -t does not test DNS or ports. It checks syntax and file paths. A port already held by another program fails only at reload or start.
  • Editing sites-enabled directly works but hides the original. Keep the real file in sites-available so you can disable a site by removing a link.
  • Reload is not instant for long connections. Old workers stay until their connections close, so a stuck download can keep an old config alive for a while.
  • Directory listings are off. A folder without an index file returns 403 or 404 unless you add autoindex on;, which you rarely want on a public site.

Troubleshooting#

SymptomLikely causeFix
nginx: [emerg] unexpected "}" in /etc/nginx/sites-enabled/example.com:12Missing ; or brace above the lineFix the file and line named, run nginx -t again
bind() to 0.0.0.0:80 failed (98: Address already in use)Apache or another proxy holds port 80Find it with sudo ss -tlnp, stop it. See fix port already in use
403 ForbiddenNo index file, or www-data cannot read the pathAdd index.html, fix permissions on every parent folder
404 Not Found for a file that existsWrong root or typo in the pathCheck error.log, it prints the full path nginx tried
“Welcome to nginx” shows for your domainDefault block matchedMatch server_name, remove the default link
duplicate default server for 0.0.0.0:80Two blocks use default_serverKeep it on one block only
nginx: [warn] conflicting server name "example.com" on 0.0.0.0:80, ignoredTwo blocks list the same nameRemove the duplicate from one file
Job for nginx.service failed after reloadConfig error or port clashRun sudo nginx -t and journalctl -u nginx -n 30

Quick reference#

bash
sudo apt install nginx
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t                          # syntax check
sudo systemctl reload nginx            # apply without dropping connections
sudo systemctl restart nginx           # full restart, cuts connections
sudo tail -f /var/log/nginx/access.log # live requests
sudo tail -n 50 /var/log/nginx/error.log
curl -I http://example.com             # headers only

Next#

Static files are only half the job, so continue with Nginx reverse proxy for a Node app.

Try it: Test, reload and check nginx

Check a new server block, apply it and confirm it serves.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1Which command checks nginx config files for errors without applying them?
2What makes a site file in sites-available actually active?
3What does try_files $uri $uri/ =404; do?
4Where does nginx write failed request details by default on Ubuntu?

Frequently asked questions

Where is the nginx config file on Ubuntu?

The main file is /etc/nginx/nginx.conf. Site files live in /etc/nginx/sites-available and are activated by symlinks in /etc/nginx/sites-enabled.

What is the difference between nginx reload and restart?

Reload applies the new config without dropping connections, and keeps the old config if the new one is invalid. Restart stops the process and starts it again, which cuts live connections.

How do I test an nginx config without restarting?

Run sudo nginx -t. It parses every included file and prints whether the syntax is ok and the test is successful.

Why do I see the Welcome to nginx page instead of my site?

The request matched the default server block. Check that server_name matches the host you typed and remove the default symlink from sites-enabled.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios