Nginx – Prevent nginx to execute images as PHP script

hackingnginxPHP

My website has been compromized by an user who uploaded an image with PHP code in it. This code allows to upload files, and he uploaded a malicious PHP script.

He was able to call his "image-php" with a GET on this URL :

http://mypwnedwebsite.com/image.jpg/.php

How can I configure nginx to prevent this behaviour? I mean, with a simple /.php, it acts as everything was PHP, which is wrong from my point of view.

I actually have a "classical" nginx 1.6.2 configuration, and I think this part is the most relevant :

location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_read_timeout 120;
        include /etc/nginx/fastcgi_params;
    }

Best Answer

This should work.

location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_read_timeout 120;
        include /etc/nginx/fastcgi_params;
        try_files $uri $uri/ /404.html;
    }

It tries to find $uri, if not a folder, if not 404 error is thrown.