Sub topic 2
Server blocks and virtual hosts
This chapter assumes you have Nginx installed and running, can edit files with sudo, and understand HTTP requests and DNS names. Run sudo nginx -t after each change, as described in the previous chapter.
Server blocks
A server block is a server { ... } section that handles requests for one or more host names. Nginx picks the block by matching the Host header of each request against server_name. This is how one Nginx instance can host several sites, which is called virtual hosting.
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}Location blocks
Inside a server block, each location block handles a group of URI paths. Nginx chooses one location with these rules:
- An exact match (
location = /path) wins immediately. - Otherwise, Nginx remembers the longest prefix match (
location /api/). - Regular expression locations (
~or~*) are then checked in file order, and the first match wins unless the longest prefix used^~.
Serving static files
The root directive sets the folder that holds the files. try_files checks for the request as a file, then as a directory, and returns 404 if neither exists.
Reverse proxying
A reverse proxy forwards a request to another program, such as an application listening on a local port. The proxy_pass directive names that program, and proxy_set_header passes along details the application needs.
location /api/ {
proxy_pass http://127.0.0.1:3000;
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;
}Exercise
A request for http://example.com/api/users arrives. Given the block above, which location handles it, and where does the request go?
Show answer
The /api/ location handles it because its prefix is longer than the / prefix. Nginx forwards the request to the application at 127.0.0.1:3000.