Exclude fastcgi from running php on an specific folder

user191251 asked:

Users can upload files on my webserver to a specific directory. In order to be more secure I want to exclude php-fastcgi from parsing PHP scripts in that specific directory.

directory = /server/files/

location ~ \.php$ {
   try_files $uri =404;
   include /etc/nginx/fastcgi_params;
   fastcgi_pass unix:/var/run/php-fastcgi/php-fastcgi.socket;
   fastcgi_index index.php;
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_nam$

How can I do it?

My answer:

There are many ways to do this, but just not loading PHP files in a particular folder is not enough. Someone could upload a file with a .jpg extension that actually contains PHP code and then execute it.

So we’ll do two things:

  1. First, only execute files if they have a .php extension. Add into your PHP location:

       fastcgi_split_path_info ^(.+\.php)(/.+)$;

    Here, any file that doesn’t end in .php will instead be routed to index.php of your application, with the filename set in $_SERVER[‘PATH_INFO’]. What happens then depends on how your application handles this. It may deliver a 404, or serve your home page, for instance.

  2. Don’t execute PHP files in a particular folder at all (your original question):

    location /uploads {
        location ~ \.php$ {return 403;}

    Hopefully what this does is obvious.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.