In NGINX, both “root” and “alias” directives are used to specify the file system path for serving files. However, they have some differences in how they handle the file path.
1. “root” directive:
The “root” directive in NGINX is used to define the root directory of a website. It sets the base directory from which NGINX will serve files. When a request is made for a file, NGINX combines the root path with the URL to determine the actual file path. For example, if the root directive is set to “/var/www/html” and a request is made for “/index.html,” NGINX will look for the file at “/var/www/html/index.html”.
Here’s an example of using the “root” directive in an NGINX configuration:
2. “alias” directive:
The “alias” directive is used to specify an exact location of a file or directory on the file system. It is similar to “root” but allows more flexibility in mapping the URL path to the file system path. With “alias,” you can define custom mappings and handle more complex URL structures.
Unlike the “root” directive, which appends the requested URL to the root path, the “alias” directive replaces the matching part of the URL with the specified file system path. This is useful when you want to serve files from a different location or when dealing with URL rewriting.
Here’s an example of using the “alias” directive in an NGINX configuration:
server {
listen 80;
server_name example.com;
root /var/www/html;
location / {
# Additional directives for handling requests
}
}
In the above example, requests to “/static/file.txt” would be mapped to “/var/www/static/file.txt” on the file system, and requests to “/images/image.jpg” would be mapped to “/var/www/images/image.jpg”.
To summarize, the “root” directive is typically used to define the base directory for serving files, while the “alias” directive is used for more specific mapping of URLs to file system paths.
server {
listen 80;
server_name example.com;
location /static/ {
alias /var/www/static/;
}
location /images/ {
alias /var/www/images/;
}
location / {
# Additional directives for handling requests