Default NGINX Catch All

April 11, 2017

When setting up a simple server to use for my own stuff, be it development, serving small websites or for testing things, I like to be versatile and after using Laravel Valet locally for development and being used to the simplicity of it just working, I decided to have a similar setup for my server.

So I built this default NGINX config file that will load up any site point to the server, provided I create a folder with the same domain name first.

To get this done just create the file:

/etc/nginx/conf.d/90-default.conf

The filename can be anything you want, as long as it ends in .conf, the only consideration you need to have is that it should be the last loaded file by NGINX, the reason why I have the 90- in front of it, I use that numbering to force my config files to load in a specific order.

This is needed when you have other sites you wouldn't want to get picked up by this default one such as if they are using SSL (which they should).

Now paste the code below into it:

server {
  listen 80;
  listen [::]:80;

  server_name   ~^(www\.)?(?<domain>.+)$;

  root /var/www/vhosts/$domain/public/;
  index index.html index.htm index.php;

  access_log /var/log/nginx/access.log main;
  error_log /var/log/nginx/error.log;

  proxy_ignore_client_abort on;

  location / {
    try_files $uri $uri/ /index.php?$query_string;
  }

  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_ignore_client_abort on;
    include fastcgi_params;
  }

}

After this is in place just reload NGINX and you all you have to do to get a new site going, is create a folder domain.com/public from which to serve the files, if it's a Laravel project the public folder will be there already, if not then make sure you have the index file inside the public folder.

Make sure you check all the paths, the code above matches what I use on my server, but your setup may be slightly different.

Posted: Apr 11, 2017