NGinx Locations for Multiple Dynamic Sites

Skip to the Important Code

Nginx is not only a fast server for single production sites but also a robust development server, with the right settings. With a default Nginx install, the /etc/nginx/sites-available/default serves overall index files for folders but doesn’t resolve queries to dynamic files. To fix this, create locations for each dynamic site.

The default Nginx file linked here with all the important pieces, port declaration, root, index files, and locations. Locations are where Nginx resolves browse requests for files in the targeted folder (in this case the root /). The examples on the Nginx page, don’t offer too much context about how various methods can work.

Locations standard code

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ =404;
	}

With just the try_files $uri, the server only resolves to files directly in the browser URL and that’s it, limiting most modern CMSs. These location sections function similar to Apache’s .htaccess files so we need a directive that properly targets WordPress’ startup index.php for queries. (Here, all the directives are in one place though.)

Often when serving multiple CMSs on Nginx multiple config files will be added to sites-available (and linked in sites-enabled) but in this case we aren’t really making multiple sites so much as enabling the same CMS in multiple directories. When testing, the easiest method was to add one location section for each WordPress install using the syntax below.

Locations for Dynamic Sites (without needing multiple server blocks)

	location /wordpresssites/siteone.com {
		# First attempt to serve request as file or
		# serve from the WordPress startup file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ /wordpresssites/siteone.com/index.php?q=$uri$args;
	}

In this way, when navigating to http://localhost/wordpresssites/siteone.com the server resolves requests to the index.php as expected. Want to setup multiple WordPress sites? Or another PHP CMS? Just copy the section and rename as needed. Make sure to restart Nginx!

sudo service nginx restart

or

sudo systemctl status nginx

Have another way of approaching these directives? Comment below!