Server Blocks and Locations

Harry · 12 Sep 2026 · 14 views

Serving Two Sites on One Server

Create a config per site in sites-available, then symlink it:

# /etc/nginx/sites-available/example.com
server {
    listen 80;
    server_name example.com www.example.com;

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

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

How Location Matching Works

location /            { ... }   # prefix, catches everything
location /assets/     { ... }   # more specific prefix wins
location = /about     { ... }   # exact match only
location ~ \.php$    { ... }   # regex (case-sensitive)
location ~* \.(png|jpg)$ { ... }  # regex (case-insensitive)

Order of evaluation: exact =, then longest prefix, then regexes (in order). The most specific rule handles the request.

Redirects and Default Site

# send everything to HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

# catch-all for unknown hosts (default_server)
listen 80 default_server;
return 444;   # close connection without a response

Key Points

  • Server blocks = virtual hosts; locations = path rules.
  • Know the location precedence or your regex will unexpectedly win.
  • Use default_server with return 444 to reject unknown hostnames.
Share this post:

Comments (0)

Please login or register to comment.