Apache-esqe Nginx Setup For PHP

If you’re here looking for the config file you’ll need, it’s directly below here. If you want the story behind why I made it and am now posting it, keep reading.

This assumes that you’re using php5-fpm to serve php.

This Is The Nginx Config You’re Looking For

 1 server {
 2     listen 80;
 3     root /path/to/your/folder/;
 4     server_name your.domain.tld;
 5     index index.php;
 7     # In case you have any .htaccess files carrying over
 8     location ~ /\.ht {
 9         deny all;
10     }
12     # allow all ".php" files to be executed
13     location ~ \.php {
14         fastcgi_pass;
15         include fastcgi_params;
16     }
18     # This is for use with any frameworks that rewrite urls (pretty urls)
19     # that don't necessarily end with ".php"
20     #location ~ ^/(.*)$ {
21     #    # Serving non-php files makes fpm not happy, so exlude them from being passed
22     #    location ~ \.[^css|js|jpg|jpeg|png|gif]$ {
23     #        fastcgi_pass;
24     #        include fastcgi_params;
25     #    }
26     #    try_files $uri /index.php; # add any params your framework needs here
27     #}
28 }

The Story

Recently I was hacking on something for Houston Hackaton and our group was ready to present, we just needed to throw our project on publicly-accessible server and we were ready to go.

“Hey, I have two of those sitting around not doing much, I’ll just throw it on one of them!” I said. We were already using one of them to host our code via git (not wanting to use github because for various reasons).

However. I had recently moved both my servers to Nginx. While i’m enjoying the performance improvemnt and overhead memory savings, it can be a PITA to configure for people new to Nginx.

We were using the Slim Framework to make the development go a little faster, and it uses url rewriting to support it’s routes.

“Ok, fine, I’ll just throw a ‘try_files’ in there and have it default to index.php” I thought. Not so fast there, kid. By default (and for very good security reasons) php5-fpm doesn’t allow access to not-specifically-requested files. Here’s a really good explaination as to why This meant that We were having problems with assets loading.

So that’s my story. I added an extra location check to not pass the execution off to php5-fpm if it’s not supposed to be a php file (i.e. specifically has a non-php extension).


blog comments powered by Disqus