All Articles

Nginx per-site configuration

Somehow I wasn’t able to find this old mechanic in the documentations and within the first page of google results while looking for it for a memory refresh, so here we go with a rustic explanation, mostly for myself

There is a modular way to write nginx.conf blocks (http location config blocks for example), in a per-site fashion (similar approach as using ‘a2ensite’ and ‘a2dissite’ in apache)

This is helpful to keep an easy to maintain conf file when you have multiple sites/domains/subdomains configurations in the same server.

Quick how to

Change the site config at /sites-available/ and then make sure that the symlink to that file exists at /sites-enabled/, if it doesn’t create it with ln -s, example:

ln -s /etc/nginx/sites-available/mysite-production /etc/nginx/sites-enabled/

Then restart nginx

How it works

Nginx consists of modules which are controlled by directives specified in the configuration file that you can usually find at /etc/nginx/nginx.conf\

A way to load the per-site configuration is having this at the bottom in that file:

location @mysite_production {
  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/sites-enabled/*;
}

so it will include the configuration from the files found in that folder there, which are actually symlinks to the ones at /sites-available folder, more about that next.

How to update them

The way that you can opt-in which one to include in the live configuration is adding or removing symlinks from /sites-available/ to /sites-enabled/

If you update the config file located at /sites-available/mysite-production it will be included in the main nginx configuration only if the symlink exists in the /sites-enabled/ folder. Changes will be reflected at sites-enabled since the symlink just links to the original file from sites-available

That way you can serve multiple configurations, and enable/disable them to quickly test stuff or to scope per-site or even per-environment configurations.

To create a symlink you can write something like this:

ln -s /etc/nginx/sites-available/mysite-production /etc/nginx/sites-enabled/

And to remove it just go with the old rm or unlink command, pointing to the symlink path.

After that make sure to restart nginx to pick up the config changes sudo service nginx restart