Setup Mass Dynamic Virtual Hosts on Nginx
Apache has a handy feature that allows you to dynamically serve a domain without having to create a virtualhost for each time, called Dynamic Virtual Hosts. Nginx doesn’t have this feature built in, but it does gives you the tools you need to to set it up in no time. Here is a guide to how I got it working on my server after I transitioned my site from Apache to Nginx.
There are a few example of how to setup dynamic virtual hosts on Nginx, but none of them did exactly what I wanted. Here were my requirements:
- Serve a domain i.e.
/var/www/example.com/public_htmlwithout having to update the server config or restarting Nginx.
- Redirect www requests to non-www.
- Include PHP Fastcgi config.
To setup this in nginx all you have to do is edit your default nginx server config file (usually
/etc/nginx/sites-enabled/default) in a text editor (I use VIM) to look like the below (changing where necessary to suit your setup):
you can easily override this default server config on a case by case basis by creating a new server block where you explicitly define the server_name. Nginx will load this server config before a server_name matched with regular expressions (As defined in the docs):
Noticed a typo or error in this post? Fork and edit it on Github!