The “include” directive is one of the most valuable and powerful directives when configuring NGINX. In this tutorial, we will explore what this directive entails and how to use it to extend and configure the power of NGINX.
Requirements:
To follow along with this tutorial, you need to have the following:
- Basic understanding of Linux terminal commands.
- Installed NGINX Web Server on your system.
Let’s dive in!
NGINX Include Directive
The “include” directive is a handy feature that allows us to break down the NGINX configuration into smaller, reusable parts. This can drastically improve the readability of the configuration and make it easier to manage.
Using the “include” directive, we can insert the content of another file into the NGINX configuration file. It is good to keep in mind that the file that you wish to include should contain valid NGINX configuration and directives.
The syntax of the “include” directive is as shown in the following:
Where the path/to/file can be an absolute or relative file path within the filesystem.
How to Use the NGINX Include Directive
Suppose we have several server blocks in our NGINX configuration, each using the same list of directives for logging.
Instead of writing the logging directives in each server block, we can write them once in a separate file and include that file in each server block.
We can start by creating the “logging.conf” file which stores the logging directives in the /etc/nginx/conf.d/ directory.
$ sudo nano /etc/nginx/conf.d/logging.conf
We can then add the logging blocks as follows:
error_log /var/log/nginx/error.log;
Once we define our configuration blocks, we can save the file and close the editor.
Then, we can include logging in the main configuration file or any conf file as shown in the following:
listen 80;
server_name example.com;
include /etc/nginx/conf.d/logging.conf;
location / {
root /var/www/html;
}
}
Using the given syntax, we can access the “access” and “error” log directives which are defined in the “logging.conf” file.
Including Multiple Files
We can also use the wildcard characters in the “include” directive. This allows us to include multiple files that match a specific pattern.
For example:
The previous entry allows us to include all files that end with “.conf” in the /etc/nginx/conf.d/ directory.
Once you made changes to the NGINX configuration, we can verify it for syntax errors using the following command:
If the configuration is valid, you should see an output as follows:
Finally, reload the Nginx server to apply the changes using the following command:
Conclusion
This tutorial explored how to work with the “include” directive in NGINX. The “include” directive is a powerful feature in NGINX that can make your configuration more manageable and readable.