Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 30 ยท Real-World Projects

Project: Host a Static Site with HTTPS and Caching

Build a complete static-site setup twice, on nginx and on Apache: HTTPS, www redirect, custom 404, cache headers, compression and security headers.

Time to put the pieces together. In this project you will host a small static website (HTML, CSS, JavaScript and images, no backend) for the domain example.com, and you will write the same setup twice: once for nginx and once for Apache. By the end the site will redirect to HTTPS and to one canonical host name, cache assets for a year and HTML for no time at all, show a friendly 404 page, compress text, refuse to serve dotfiles and hide the server version.

The point is less the static site than the checklist. Almost every production configuration you meet repeats these same twelve decisions, and having both servers side by side shows which directive does which job. Each earlier lesson explains one of them in depth; this page links to them as you go.

The real configuration appears in read-only blocks, because the site cannot run a web server or issue certificates. The interactive example is a JavaScript stand-in: a checklist scorer that looks for key directives in a config. It is a study aid, not a validator, so always finish with nginx -t or apachectl configtest and real curl requests on your own server.

The plan

HTTPS everywhere HTTP redirects. One canonical host.
Smart caching Fingerprinted assets for a year, HTML revalidated.
Safe defaults Headers, no dotfiles, no version, no listings.
Friendly errors A custom 404 page and old URLs redirected.

Same goals on both servers. Only the spelling differs.

1 / 2

The site and its layout

Assume this folder, deployed by copying files, with build tools that fingerprint file names under /assets/ (for example app.4f2a9c.js, so a new build always has a new name):

Text
/var/www/example.com/public/
  index.html
  about/index.html
  404.html
  assets/
    app.4f2a9c.css
    app.7d1e3b.js
    logo.9c0a11.svg

Certificates come from Let's Encrypt and live in /etc/letsencrypt/live/example.com/ (see HTTPS, TLS and Let's Encrypt). The canonical address is https://example.com/; both http:// and www. must lead there with a 301 redirect, so search engines see one site (details in Redirects and Rewrites).

Part 1: nginx

Put shared security headers in one snippet. This matters because of the add_header rule from Hardening and Security Headers: a location that sets its own add_header loses every inherited one, so each such location includes the snippet again.

NGINX
# /etc/nginx/snippets/security-headers.conf
add_header Strict-Transport-Security "max-age=300" always;    # raise to 31536000 once everything works
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

The site itself, /etc/nginx/conf.d/example.com.conf:

NGINX
# 1. Plain HTTP: answer certificate checks, redirect everything else
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    location ^~ /.well-known/acme-challenge/ {
        root /var/www/letsencrypt;
    }
    location / {
        return 301 https://example.com$request_uri;
    }
}

# 2. HTTPS on the wrong host name: send www to the canonical name
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name www.example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    return 301 https://example.com$request_uri;
}

# 3. The real site
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

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

    server_tokens off;

    gzip on;
    gzip_types text/css application/javascript application/json image/svg+xml;

    include snippets/security-headers.conf;

    error_page 404 /404.html;

    # old URL, moved for good
    location = /about.html {
        return 301 /about/;
    }

    # fingerprinted files never change: cache for a year
    location /assets/ {
        add_header Cache-Control "public, max-age=31536000, immutable" always;
        include snippets/security-headers.conf;
        try_files $uri =404;
    }

    # never serve hidden files (certificate checks use port 80 above)
    location ~ /\. {
        deny all;
    }

    # everything else (HTML): store, but ask the server every time
    location / {
        add_header Cache-Control "no-cache" always;
        include snippets/security-headers.conf;
        try_files $uri $uri/ =404;
    }

    location = /404.html {
        internal;
        add_header Cache-Control "no-cache" always;
        include snippets/security-headers.conf;
    }
}

Let's check some decisions. Server 1 uses ^~ on the challenge location, so a regex location can never steal certificate checks (see Location Blocks and Matching Order). Server 2 exists only to redirect; it needs a certificate, because a browser completes the TLS handshake before it can see any redirect. In server 3, try_files $uri $uri/ =404 turns a missing file into a clean 404 which error_page replaces with your page, and internal stops people from requesting /404.html as if it were a normal page. no-cache does not mean "do not store": it means "revalidate before use", so browsers send a cheap conditional request and usually get a 304 Not Modified (see Static Files, Caching and MIME Types). The HTTP/2 line http2 on; needs nginx 1.25.1 or newer; on older versions write listen 443 ssl http2; instead (see HTTP/2, HTTP/3, gzip and Brotli).

Part 2: Apache

Enable the modules first (names are for Debian and Ubuntu):

Terminal
sudo a2enmod ssl headers http2 deflate
sudo a2dismod mpm_prefork && sudo a2enmod mpm_event     # HTTP/2 needs a threaded MPM

Global hardening, for example in /etc/apache2/conf-available/hardening.conf (enable it with a2enconf hardening):

APACHE
ServerTokens Prod
ServerSignature Off
TraceEnable Off

The site, /etc/apache2/sites-available/example.com.conf:

APACHE
# 1. Plain HTTP: redirect everything to the canonical HTTPS address
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

# 2. HTTPS on the wrong host name: send www to the canonical name
<VirtualHost *:443>
    ServerName www.example.com
    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    Redirect permanent / https://example.com/
</VirtualHost>

# 3. The real site
<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/example.com/public

    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    Protocols h2 http/1.1

    <Directory "/var/www/example.com/public">
        Options -Indexes
        AllowOverride None
        Require all granted
    </Directory>

    ErrorDocument 404 /404.html
    Redirect permanent /about.html /about/

    Header always set Strict-Transport-Security "max-age=300"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"

    # fingerprinted files never change: cache for a year
    <LocationMatch "^/assets/">
        Header set Cache-Control "public, max-age=31536000, immutable"
    </LocationMatch>

    # HTML: store, but ask the server every time
    <FilesMatch "\.html$">
        Header set Cache-Control "no-cache"
    </FilesMatch>

    # never serve hidden files or folders
    <DirectoryMatch "/\.(?!well-known)">
        Require all denied
    </DirectoryMatch>
    <FilesMatch "^\.">
        Require all denied
    </FilesMatch>

    AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json image/svg+xml
</VirtualHost>

Notice how much is the same idea in a different spelling. Apache's Header always set is the counterpart of nginx's add_header ... always, and there is no inheritance trap, because headers from Header set in matching containers are merged rather than replaced. AllowOverride None switches .htaccess off, which is both a security and a speed decision (see .htaccess, Directory Rules and AllowOverride). Options -Indexes is nginx's default autoindex off, spelled out. Here the plain-HTTP host redirects everything, including certificate checks. Let's Encrypt follows that redirect to HTTPS, which is why the dotfile rule above leaves .well-known alone and why you would point certbot's webroot method at the public folder (-w /var/www/example.com/public); the --apache plugin handles it for you. A real deployment would also add certbot's recommended TLS settings; certbot --apache or certbot --nginx writes them for you and can be rerun safely.

Note the HSTS value of 300 seconds. HSTS is sticky: if you set a year and then your certificate breaks, visitors cannot click through the warning. Deploy with five minutes, test the HTTPS site and its subdomains, then raise the value in steps.

Enable, test, verify

Terminal
# nginx
sudo nginx -t && sudo systemctl reload nginx

# Apache (Debian)
sudo a2ensite example.com && sudo a2dissite 000-default
sudo apachectl configtest && sudo systemctl reload apache2

Then check the behavior from the outside, one claim at a time:

Terminal
curl -sI http://example.com/page                # expect 301 -> https://example.com/page
curl -sI https://www.example.com/page           # expect 301 -> https://example.com/page
curl -sI https://example.com/                   # expect 200, Cache-Control: no-cache, security headers, no version in Server
curl -sI https://example.com/assets/app.7d1e3b.js    # expect immutable, max-age=31536000
curl -sI https://example.com/nothing-here       # expect 404 (and your custom page in the body)
curl -sI https://example.com/.git/config        # expect 403 or 404, never 200
curl -sI -H "Accept-Encoding: gzip" https://example.com/assets/app.4f2a9c.css | grep -i content-encoding

If a result is wrong, the order in Logs and Troubleshooting applies: reproduce with curl, read the error log, check what the server loaded (nginx -T or apachectl -S), change one thing.

Stand-in: score a config against the checklist

The checklist behind this project is twelve items. This JavaScript tool looks for the key directive of each item in a config text, for both servers. It is deliberately simple (regular expressions, not a parser) and is only meant to show how a review checklist can be automated. The nginx first draft is the kind of file people ship on day one; the finished versions are abbreviated copies of the ones above.

JS Stand-in: checklist scorer

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

No output.

A pattern match proves only that a line exists, not that it is correct or in the right block. A scorer like this is useful as a guard in CI (see Reloads, Zero-Downtime Deploys and Containers), but the real proof is always the curl checks above.

Extend the project

Once it works, try these extensions, each of which maps to a lesson:

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the www server block need a TLS certificate even though it only redirects?

    A visitor to https://www.example.com first negotiates TLS. Without a valid certificate for that name the browser shows a warning and never sees the 301.
  2. 2. Why is Cache-Control: public, max-age=31536000, immutable safe for /assets/ but not for HTML pages?

    A new build produces new asset file names, so old copies can safely live a year. HTML is requested at stable URLs, so it is revalidated each time.
  3. 3. In the nginx config, why does each location that sets Cache-Control also include the security headers snippet?

    add_header inheritance is all-or-nothing per level. Including the same snippet again restores the shared headers.
  4. 4. What does error_page 404 /404.html; combined with location = /404.html { internal; } achieve?

    error_page serves the file with the 404 status. The internal location only allows that internal redirect, so /404.html requested by a visitor gets a 404 of its own.
  5. 5. Why use a small HSTS max-age at first?

    Once a browser has remembered HSTS it will not allow a click-through for certificate errors until the time expires.

Summary

  • One site, two spellings: nginx server and location blocks, Apache VirtualHost, Directory, LocationMatch and FilesMatch.
  • Three virtual hosts per site are common: plain HTTP (redirect), the non-canonical host (redirect, with a certificate), and the canonical host (the real content).
  • Fingerprinted assets get immutable and a year; HTML gets no-cache so it is revalidated.
  • Security basics: HSTS (start small), nosniff, framing and referrer headers, hidden version, no listings, no dotfiles, AllowOverride None.
  • In nginx, repeat the shared header snippet wherever a location adds its own add_header.
  • Always finish with the config test and curl -I checks from outside.

Next: Project: A PHP Application with Clean URLs.