Sub topic 3
Giving Each Site Its Own Document Root
Assume Nginx is installed and running, you can use sudo, and you understand DNS, HTTP requests, and the Host header. This chapter uses the Debian and Ubuntu layout, where site files live in sites-available and enabled sites are linked from sites-enabled.
A document root is the directory from which Nginx serves a site’s files. Each site should have a separate root so that one site cannot accidentally serve another site’s content.
Mapping URLs to Files
Suppose a request arrives for:
http://example.com/about.htmlIf the server block has this root:
/var/www/example.com/htmlNginx looks for:
/var/www/example.com/html/about.htmlThe index directive provides a default file when the request names a directory. The try_files directive checks that the requested path exists and returns 404 Not Found when it does not.
Creating Separate Roots
Create one directory tree per site. The index.html files make it easy to confirm which server block answered the request.
sudo mkdir -p /var/www/example.com/html
sudo mkdir -p /var/www/example.org/html
echo '<h1>example.com</h1>' | sudo tee /var/www/example.com/html/index.html
echo '<h1>example.org</h1>' | sudo tee /var/www/example.org/html/index.html
sudo chown -R www-data:www-data /var/www/example.com
sudo chown -R www-data:www-data /var/www/example.org
sudo chmod -R u=rwX,go=rX /var/www/example.com
sudo chmod -R u=rwX,go=rX /var/www/example.orgOn some distributions, Nginx runs as the nginx user instead of www-data. Check the user directive in /etc/nginx/nginx.conf and adjust the ownership command if necessary. Nginx needs permission to read the files and to traverse every parent directory.
Writing the Server Blocks
Create /etc/nginx/sites-available/example.com with this content:
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;
}
}Create a second server block for example.org and change both server_name and root:
server {
listen 80;
listen [::]:80;
server_name example.org www.example.org;
root /var/www/example.org/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}Enable both sites and reload only after validation succeeds:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com
sudo ln -s /etc/nginx/sites-available/example.org /etc/nginx/sites-enabled/example.org
sudo nginx -t && sudo systemctl reload nginxA 403 Forbidden often means that Nginx cannot read a file, traverse a directory, or find an index file. A 404 usually means the URI does not map to a file under the selected root.
Exercise
What file does Nginx check for a request to http://example.org/images/logo.png when the server block has root /var/www/example.org/html;?
Show answer
It checks /var/www/example.org/html/images/logo.png.