$document_root
The $document_root variable returns the root directory of the current server or location block as defined in the NGINX configuration. — NGINX Core (HTTP)
Description
The $document_root variable in NGINX provides the file system path to the root directory from which files are served for a given request. This directory is typically set in the server or location block through the `root` directive. Its value is determined by the most specific `root` directive applicable to the current request. If a `root` directive exists in both the server block and the location block, the more specific location block's value will take precedence. This variable is useful for constructing file paths, especially when combined with other variables like `$uri` or `$request_filename`. When NGINX handles incoming requests, it parses the configuration and assigns the appropriate document root based on the matched location directive. If no `root` is set, the variable will return an empty string which can lead to errors if misused in configurations expecting a valid path. One important note is that if the server block defines a `root` and no specific `location` block with a `root` directive exists, all requests matching that server will use the server block's document root. The variable is often used within various NGINX directives, including `try_files`, `rewrite`, and `alias`, to alter the way requests are processed based on the defined file structure.
Config Example
server {
listen 80;
server_name example.com;
root /var/www/example.com;
location / {
try_files $uri $uri/ =404;
}
}
location /images/ {
root /var/www/images;
}
# Example usage in a log:
access_log /var/log/nginx/access.log "[$document_root]";Subsystem
httpCacheable
NoContexts
http, server, location, ifIf no root directive is defined, $document_root will be empty, which may lead to `404 Not Found` errors if referenced directly.
Be cautious when using $document_root within a `try_files` directive; this can result in unexpected behavior if paths are not correctly structured.
Mixing up `root` and `alias` directives can lead to confusion, as they handle paths differently.