Disabling php files in wordpress upload when using nginx

This isn’t well documented anywhere for nginx. In fact it is sorta hidden and hard to find. Nginx does support a way for me to disable php from being executed in my uploads directory.
The way I came across actually I am loving, as I am able to control how content is handled actually. This is a plus on the server admins end.

                # Only allow images to be viewed.
                location /wordpress/wp-content/uploads/
                {
                        types
                        {
                                image/gif       gif;
                                image/jpeg      jpeg jpg;
                                image/png       png;
                                text/plain      txt;
                        }
                
                        default_type    application/octet-stream;

                        location ~ \.php$
                        {
                                break;
                        }
                }

Simply put, I setup a location to only run on my uploads directory. Then I change the types and only defined jpg, gif and png. All other files get sent as a download. Finally since I run php as fastcgi, I setup a nested location to run for php files and tell it to stop evaluating rules.

In fact, this is all actually nested in my primary location /. I did it this way as it worked the easiest. Although I am sure I could remove that nesting.


Update on 2/14/12:

This was brought up on http://stackoverflow.com/questions/8392187/nginx-allow-only-images-from-directories-are-these-internal-locations-allowe.

The method there may not always work depending on the rest of the Nginx configuration. This is because the PHP rules would still be evaluated. You need to have it break searching rules and not evaluate any more rules. If you don’t upload any PHP files to be downloaded, then this isn’t a problem. That solution also is cleaner if you have multiple upload locations or directories you need to protect rather than duplicating the code for each directory.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.