However, writing directly to /etc/nginx/nginx.conf is not a good idea because if we upgrade NGINX, the nginx.conf file may get replaced. Also, if the server has to handle many services, the large number of server blocks in the file will make it hard to read and maintain. Therefore, it's good practice to split configurations for different services into different files from the outset.
A common convention is to use two directories: /etc/nginx/sites-available and /etc/nginx/sites-enabled. You'd place the configuration for each service as separate files under the sites-available directory. Then, to enable a service, you'd create a symbolic link from the sites-enabled directory to a file in the sites-available directory. Lastly, you'd link the /etc/nginx/sites-available directory to the main configuration by adding an include entry in the configuration.
First, add the two directories:
hobnob@hobnob:$ sudo mkdir /etc/nginx/sites-available /etc/nginx/sites-enabled
Then, in the /etc/nginx/nginx.conf file, add an include directive after include /etc/nginx/conf.d/*.conf;:
...
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
...
Then, pull out each server block from within the http context and place them, as separate files, inside /etc/nginx/sites-available/. By convention, the name of the file should correspond to the domain name, but since we don't have a domain yet, we can name it api.
Just to clarify, /etc/nginx/sites-available/api should be a file with the following content:
server {
listen 80 default_server;
location / {
proxy_pass http://localhost:8080;
}
}
Now, to enable the sites, we must add to the /etc/nginx/sites-enabled directory using a symbolic link:
hobnob@hobnob:$ sudo ln -s /etc/nginx/sites-available/api /etc/nginx/sites-enabled/
An additional benefit to this approach is the separation of concerns: generic configurations reside inside the nginx.conf file and site-specific settings (for example, SSL certificates) reside within their own files. Lastly, this is similar to how virtual hosts are set up on the Apache HTTP server; thus, adopting this approach would make it easier for administrators who are accustomed to the Apache HTTP server to migrate over.
Now, we need to reload the configuration once more:
hobnob@hobnob:$ sudo systemctl reload nginx.service