Pages

12.13.2014

My perfect nginx config

Setting up web servers is a pain in the ass if you don't do it all the time.  I don't.  So I've spent the last few days trying to figure out how to configure nginx.  I have an Amazon AWS instance running a couple of low traffic sites mainly for fun.  One site in particular had some special requirements. 
  • only the index.php file should ever be executed
  • no static files are served from this site (css/html/js)
This site has a couple of composer files in the site root, and I didn't want anyone to just be able to download them.  This site also runs on a framework that uses a "front controller", meaning that one PHP file dispatches and handles all the requests.  So here's the nginx config that I came up with to do just that.

With this configuration, here's what works and what doesn't:
These work as expected:
example.com/
example.com/api/who
example.com/index.php
example.com/index.php/api/who

These are 404ed as they should be:
example.com/composer.lock
example.com/SomePHPFile.php


 server {
        listen 80;

        root /var/www/example;

        server_name example.com;

#direct all traffic to the front controller after trying files
    location / {
        index index.php;
        try_files $uri $uri/ /index.php?$args;
   }


#only redirects to the front controller will be processed.
    location ~ index\.php {
        fastcgi_pass   unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;

    }


#any path which is an actual file will get a 404
    location ~ (\.[^/]+)$ {
        return 404;
    }

}