Use "include" in nginx server block but where to save?

Call Me Hi Hi asked:

All of the examples I have seen, used “include something.conf” in the http block.

Is it possible to use “include something.conf” in the server block? If yes, where is the best practice to save the conf?

For example:

server {
    listen 80;

    include (where)/somethingcool.conf


My answer:

You can put the file wherever you want.

If you use a relative path, however, then it will be relative to the nginx configuration directory (e.g. /etc/nginx on Linux, /usr/local/etc/nginx on BSD, etc.).

I personally create a directory /etc/nginx/includes and place these configuration bits in there. For example:

server {

    include includes/listen-80;
    include includes/letsencrypt;

    return 301 https://$host$request_uri;

Where /etc/nginx/incldues/listen-80 contains:

listen 80;
listen [::]:80;

And /etc/nginx/includes/letsencrypt contains:

location /.well-known/acme-challenge/ {
    root /var/www;
    try_files $uri =404;

Of course I have many other such configuration bits.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.