Visit me elsewhere:

Nginx configuration with includes

If you’re setting up a server with both HTTP and HTTPS access you will have to define 2 server directives in your nginx configuration. Then you will define pretty much the same in both, and just add the SSL options like cert and port in your HTTPS-server. However, there is a better way. In this blog post I will explain how to efficiently use include statements in your nginx configuration to use a better configuration file structure.

A second feasible way of using includes it for redirects. Did you change (some) of your URI-structure? Did you move a file resulting in a new URI? Put them in a separate file and include it in your hosts configuration file to keep it clean.

This guide works with the debian-style configuration- and -file-structure /etc/nginx, sites-enabled, etc.

The nginx.conf file already uses includes to their best by default:

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

This also means we can not put our files we want to include inside our server directives, and only there, into the conf.d or sites-enabled folder (or not name them .conf in conf.d). So first, let us create a new folder includes (/etc/nginx/includes). Then we can create a file for our redirects in there, example.com-redirects:

location = /wordpress/page/awesomeness {
  rewrite ^ $scheme://example.com/thisis/1-awesomeness;
}

Good, we now defined a permanent redirect. We also used $scheme to redirect keeping the requesters scheme (HTTP or HTTPS?), so a user explicitly requesting HTTPS is not redirected to the new URI but HTTP. In this style, we could also keep the requesters hostname with $host.

Now we need to include them. In our sites-enabled/example.com.conf, inside the corresponding server directive(s) we include the redirects:

server {
  listen 80;
  listen [::]:80;
  server_name example.com;
  […]
  include includes/example.com-redirects;
}

This was for port 80 now, so (hopefully) HTTP. Adding the same redirects to your HTTPS server is easy: Just add the include to it as well.

The result is a good one: You know where to find your redirects and you will be faster scanning your actual server configuration, not having to scroll through all your redirects. And you edit them in one place and change them for all the matching servers.

If you have a lot of virtual hosts, a lot of redirects you may even want to create sub-folders hosts and/or redirects inside your includes directory, or just create a directory for each host in there. Just decide on a good structure for your setup and use it.