Given this nginx server block configuration, what file will nginx serve when a user accesses http://example.com/?
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
}Check the root and index directives to find the default file served.
The root directive sets the base directory for files. The index directive lists files nginx tries to serve by default. Here, index.html is the first file nginx looks for inside /var/www/html.
Where should the root directive be placed to serve files correctly for a specific location?
server {
listen 80;
server_name example.com;
location /images/ {
# Where to place root?
}
}Think about how nginx uses root for different URL paths.
The root directive can be set inside a location block to specify a different root directory for that path. This overrides the server-level root for that location.
Given this configuration, nginx returns 404 when accessing http://example.com/images/pic.jpg even though the file exists at /var/www/images/pic.jpg. What is the cause?
server {
listen 80;
server_name example.com;
root /var/www/html;
location /images/ {
root /var/www/images;
}
}Remember how nginx combines root and the request URI inside location.
When root is used inside a location, nginx appends the full request URI to the root path. So for request URI /images/pic.jpg and root /var/www/images, it constructs /var/www/images/images/pic.jpg. This file does not exist, causing 404.
You want to serve static files from /var/www/static when users access /static/ URL. Which configuration is best?
Consider how root and alias handle URI paths differently.
The alias directive replaces the location part of the URI with the specified path, so alias /var/www/static/; correctly maps /static/file to /var/www/static/file. Using root would duplicate the /static/ part in the path, causing errors.
Consider this nginx configuration:
server {
listen 80;
server_name example.com;
root /var/www/html;
location / {
root /var/www/site;
location /images/ {
root /var/www/images_root;
}
}
}What is the full filesystem path nginx will use to serve http://example.com/images/pic.jpg?
Remember that nested location blocks override the root directive independently.
The innermost location /images/ block sets root /var/www/images_root;. Nginx appends the full request URI /images/pic.jpg to this root, resulting in /var/www/images_root/images/pic.jpg.