Modern NGINX default server definition, with hostname automatically mapped to a directory

When I first decided to switch my primary web server from Lighttpd to NGINX I attempted to mimic the setup I had achieved in Lighttpd. As such, one of my first initial gripes with NGINX is that I had to create a new Virtual Host server definition for every new site I wished to add. What I really wanted was a default catch-all definition that mapped the hostname (without the www.) to a directory, while also retaining the ability to have additional site-specific definitions when needed. However, after spending a significant amount of time trying to find an existing solution, I found none that were perfect. So here is what I finally came up with myself:

server {
  listen 80 default;

  # Requires NGINX >= 0.8.25
  server_name ~^(www\.)?(?<domain>.+)$;

  root /var/www/vhosts/$domain;

  access_log /var/log/nginx/default.access.log;

  index index.php index.html index.htm;

  server_name_in_redirect off;

  # Enable rewrites for WordPress (only works if WordPress is in the site's root directory)
  try_files $uri $uri/ /index.php?q=$uri&$args;

  # Serve static files directly
  location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|mp3|wav|swf|zip|pdf|htc|flv|f4v|mov|mp4|wmv|avi|mpg|woff)$ {
    access_log off;
    expires max;
    add_header Cache-Control public;

  # Pass to php
  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/tmp/php.socket;

  location ~ /\.ht {
    deny all;


It should be noted that this config requires an NGINX version >= 0.8.25.

Also, since NGINX loads its virtual host files alphabetically, I suggest inserting this code into a file named 000-default. :)

One thought on “Modern NGINX default server definition, with hostname automatically mapped to a directory

  1. First comment! You did pick wordpress afterall. Looks great I must say. And as you’ve warned, this stuff really is geeky, little clue of what this is all about. Backend development is such a maze to me.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>