Now that we have Nginx up and running, let's configure it to serve our very first static website. Static content refers to files like HTML, CSS, JavaScript, and images that are delivered to the browser exactly as they are stored on the server. The two fundamental directives for serving static content are root and index.
The root directive specifies the document root for requests. This is the directory on your server where Nginx will look for files to serve. When a request comes in, Nginx will append the requested URI to this root path to find the corresponding file.
location / {
root /var/www/html;
}In the example above, if a user requests http://your_domain.com/about.html, Nginx will look for the file at /var/www/html/about.html. If the user requests just http://your_domain.com/, Nginx will look for an index file within the specified root directory.
This is where the index directive comes into play. The index directive defines the file(s) that Nginx should serve when a directory is requested. Nginx will try to serve these files in the order they are listed.
location / {
root /var/www/html;
index index.html index.htm;
}With this configuration, if a user requests http://your_domain.com/, Nginx will first look for index.html in the /var/www/html/ directory. If it finds index.html, it will serve that. If not, it will then try to serve index.htm from the same directory.
It's crucial to understand how these directives interact. The root directive sets the base directory, and the index directive specifies which file(s) to serve within that directory when no specific file is requested.
graph TD
A[User Request for '/'] --> B{Nginx Config?
root: /var/www/html
index: index.html index.htm}
B --> C{Look for '/var/www/html/index.html'}
C -- Found --> D[Serve index.html]
C -- Not Found --> E{Look for '/var/www/html/index.htm'}
E -- Found --> F[Serve index.htm]
E -- Not Found --> G[Return 404 Error]
You can also define root and index directives within server blocks or location blocks, allowing for more granular control over which directories and index files are served for different parts of your website or for different virtual hosts.