Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 95 ยท System Administration

Setting Up a Web Server: nginx, TLS, Let's Encrypt

Install nginx on Linux, serve several sites with server blocks, add HTTPS with Let's Encrypt and certbot, and put a reverse proxy in front of an application.

Sooner or later every Linux user puts something on the internet: a static site, an API, a Laravel or Node application. A web server is the program that listens on ports 80 and 443, understands HTTP, and either serves files itself or forwards requests to your application. nginx is one of the most common choices because it is small, fast and configured with a readable text format.

This lesson installs nginx, serves two sites from one machine with virtual hosts (nginx calls them server blocks), adds free HTTPS certificates from Let's Encrypt with certbot, and then turns nginx into a reverse proxy in front of an application. The sandbox has no nginx, no root and no network, so the server commands are read-only; the runnable examples use openssl and shell tools to explore certificates and to check configuration files. It builds on Packages, Services and systemd, Networking Basics and Users, Groups and sudo.

Installing and starting nginx

On Debian and Ubuntu:

CONSOLE
$ sudo apt update
$ sudo apt install nginx
$ sudo systemctl enable --now nginx     # start now and at every boot
$ systemctl status nginx
$ curl -I http://localhost              # expect: HTTP/1.1 200 OK

On Fedora and RHEL the package is also nginx, installed with dnf. If a firewall is running, open the ports: sudo ufw allow 'Nginx Full' (Ubuntu) or sudo firewall-cmd --permanent --add-service={http,https} followed by --reload (RHEL family).

The configuration lives in /etc/nginx/:

Path Purpose
nginx.conf Main file; global settings and an include for the rest
sites-available/ One file per site (Debian family)
sites-enabled/ Symlinks to the sites that are switched on
conf.d/*.conf Extra snippets (the layout on RHEL-style systems)
/var/log/nginx/ access.log and error.log

Enabling a site is just creating a symbolic link (see Links), so disabling it is deleting the link. Always test before reloading:

CONSOLE
$ sudo nginx -t                  # syntax check; prints "syntax is ok" or the error and line
$ sudo systemctl reload nginx    # apply the new config without dropping connections

reload starts new workers with the new configuration and lets old ones finish their requests. Use restart only when you must.

Virtual hosts: many sites, one server

A browser sends the name it wants in the Host header. nginx picks the server block whose server_name matches. This is how one IP address hosts many sites.

flowchart LR
  B["Browser<br/>Host: blog.example.com"] --> N["nginx :80"]
  N -->|"server_name blog.example.com"| S1["/var/www/blog"]
  N -->|"server_name shop.example.com"| S2["/var/www/shop"]
  N -->|"no match: default_server"| S3["/var/www/default"]

nginx matches the Host header against each server block's server_name and serves that site's files.

A complete static site in /etc/nginx/sites-available/blog.example.com:

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

    root /var/www/blog;
    index index.html;

    location / {
        try_files $uri $uri/ =404;       # file, then directory, then 404
    }

    location ~* \.(css|js|svg|png|jpg|woff2)$ {
        expires 30d;                     # let browsers cache assets
        add_header Cache-Control "public";
    }

    access_log /var/log/nginx/blog.access.log;
    error_log  /var/log/nginx/blog.error.log;
}

Then enable and test it:

CONSOLE
$ sudo mkdir -p /var/www/blog && echo '<h1>Hello</h1>' | sudo tee /var/www/blog/index.html
$ sudo ln -s /etc/nginx/sites-available/blog.example.com /etc/nginx/sites-enabled/
$ sudo nginx -t && sudo systemctl reload nginx
$ curl -H 'Host: blog.example.com' http://127.0.0.1/      # test without DNS

The curl -H 'Host: ...' trick tests a virtual host before the DNS record exists. Two details trip people up: the nginx worker user (www-data on Debian) needs read permission on the files and execute on every directory above them (see Permissions), and a missing root or wrong location produces 403 or 404 entries in error.log that tell you exactly which file it tried.

Because configuration is text, you can analyse it with the tools you already know. This script lists the sites in a config and checks that the braces balance, which catches the most common typo before nginx -t does:

Bash Reading an nginx config with awk

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

HTTPS and Let's Encrypt

Plain HTTP can be read and altered by anyone on the path. HTTPS wraps the connection in TLS, which needs a certificate: a file that ties your domain name to a public key, signed by a certificate authority (CA) that browsers trust. Let's Encrypt is a free, automated CA. Its certificates last 90 days or less and are meant to be renewed automatically.

Before you start, two things must be true: the domain's DNS A/AAAA record points to your server, and port 80 is reachable from the internet, because Let's Encrypt proves you control the domain by fetching a small file from http://yourdomain/.well-known/acme-challenge/ (the HTTP-01 challenge).

CONSOLE
$ sudo apt install certbot python3-certbot-nginx
$ sudo certbot --nginx -d blog.example.com -d www.blog.example.com

certbot asks for an email address, obtains the certificate, rewrites the nginx server block to listen on 443, and offers to redirect HTTP to HTTPS. The certificate and key land in /etc/letsencrypt/live/blog.example.com/ (fullchain.pem and privkey.pem). Renewal is installed as a systemd timer or cron job; test it with a dry run:

CONSOLE
$ sudo certbot renew --dry-run
$ systemctl list-timers | grep certbot
$ sudo certbot certificates          # lists domains and expiry dates

The configuration certbot produces looks like this, and you can write it by hand just as well:

NGINX
server {
    listen 80;
    server_name blog.example.com www.blog.example.com;
    return 301 https://blog.example.com$request_uri;    # send everyone to HTTPS
}

server {
    listen 443 ssl;
    http2 on;
    server_name blog.example.com;

    ssl_certificate     /etc/letsencrypt/live/blog.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/blog.example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

    add_header Strict-Transport-Security "max-age=31536000" always;

    root /var/www/blog;
    index index.html;
}

Two rules matter for the files: fullchain.pem (your certificate plus the intermediate CA) is public, but privkey.pem must be readable by root only, and you never copy it into a repository or ticket. Wildcard certificates (*.example.com) need the DNS-01 challenge instead, which proves control by creating a TXT record.

You can inspect any certificate with openssl. The sandbox cannot reach Let's Encrypt, but it can create a self-signed certificate (a certificate that signs itself, good for local testing and not trusted by browsers) and read its fields, which are the same ones you would read in a real certificate:

Bash Create and inspect a certificate with openssl

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

In a real deployment, openssl s_client -connect blog.example.com:443 -servername blog.example.com shows the chain the server sends, and openssl x509 -noout -enddate on the certificate file tells you when it expires. An expired certificate is one of the most common outages, which is why certbot renew --dry-run belongs in your checklist.

nginx as a reverse proxy

Most applications (Node, Python, Java, PHP-FPM, Laravel's artisan serve) should not face the internet directly. They listen on a local port such as 127.0.0.1:3000, and nginx in front handles TLS, compression, static files and slow clients, then proxies the request through.

NGINX
server {
    listen 443 ssl;
    server_name app.example.com;
    ssl_certificate     /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;

    location /static/ {
        alias /var/www/app/static/;          # nginx serves files itself
    }

    location / {
        proxy_pass http://127.0.0.1:3000;     # everything else goes to the app
        proxy_set_header Host              $host;
        proxy_set_header X-Real-IP         $remote_addr;
        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

The proxy_set_header lines matter: without them the application sees every request coming from 127.0.0.1 over plain HTTP, so logs show the wrong client address and redirects may point at http://. For WebSockets add proxy_http_version 1.1; plus the Upgrade and Connection headers. To balance several instances, define an upstream app { server 127.0.0.1:3000; server 127.0.0.1:3001; } block and use proxy_pass http://app;.

A quick troubleshooting ladder when something is wrong:

  1. sudo nginx -t for syntax.
  2. sudo tail -f /var/log/nginx/error.log while you repeat the request.
  3. ss -tlnp | grep -E ':80|:443|:3000' to see what is actually listening (is the app up?).
  4. 502 Bad Gateway means nginx could not reach the app; 504 means the app answered too slowly; 403 and 404 usually mean permissions or a wrong root.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does nginx decide which site to serve when several server blocks listen on port 80?

    The browser sends the wanted name in the Host header. Only when no server_name matches does nginx use the default server for that port.
  2. 2. What should you run before applying a changed nginx configuration, and how do you apply it without dropping connections?

    nginx -t checks syntax and prints the problem line. reload lets old workers finish their requests while new ones use the new config.
  3. 3. Which two files does certbot create for a domain, and which one must stay private?

    The certificate chain is sent to every visitor, while anyone with the private key can impersonate your server.
  4. 4. Why do reverse-proxy configurations add proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for?

    Behind a proxy all connections come from the proxy itself. The header carries the real client address to the application.
  5. 5. A Let's Encrypt HTTP-01 challenge fails. Which problem is most likely?

    The CA must fetch a file from http://domain/.well-known/acme-challenge/. Wrong DNS or a closed port 80 stops that.

Summary

  • Install with apt install nginx (or dnf), enable with systemctl enable --now nginx, and test configuration with nginx -t before reload.
  • Virtual hosts are server blocks selected by server_name; on Debian you enable one by linking sites-available into sites-enabled.
  • The worker user needs read access to the files and execute access on the directories above them.
  • Let's Encrypt gives free 90-day certificates; certbot --nginx -d DOMAIN obtains and installs one, and certbot renew --dry-run tests renewal. Keep privkey.pem private.
  • openssl x509 reads certificate fields (subject, SAN, dates); self-signed certificates are for testing only.
  • A reverse proxy uses proxy_pass plus Host, X-Real-IP, X-Forwarded-For and X-Forwarded-Proto headers. 502 means the app is down, 504 that it is too slow.

Next: File Sharing: NFS, Samba and rsync Servers