3

Say my website allows users to create directories as well as upload to a directory called "/uploads", like so:

/uploads/user_created_folder_1

/uploads/user_created_folder_2

/uploads/user_created_folder_3

... so on and so forth

How do I prevent any potentially malicious script from being executed in "/uploads" as well as all of its subdirectories?

Is the following code in the server block correct?

location /uploads/.*.(php|pl|py|jsp|asp|sh|cgi)$ {
                return 403;
                error_page 403 403.html;
        }

Thanks very much!

7

First of all, nginx does not execute scripts. Under some conditions it could proxy request to other server that execute script. Most commonly condition is extension of file in request and typical nginx config block looks like this:

location ~* \.php$ {
  fastcgi_pass backend;
  ...
}

So your question should be: how to prevent proxying requests to folder /uploads/? And with this typical config answer is as simple as:

location ^~ /uploads/ {
}

which means: if request to folder uploads, just serve them as static files, do not try to look for regexp locations for them (that require you to understand different types of nginx locations).

If your config is much different from typical one, we need to see it to give you proper answer.

  • Thank you @alexeyten. Should the code (location ^~ /uploads/ { }) be placed before or after the fastcgi block of code? Or does it not matter? Thanks. – Honey Badger Mar 31 '14 at 8:20
  • 2
    It doesn't matter. Nginx checks prefix locations before regexp's ones. – Alexey Ten Mar 31 '14 at 8:30
  • Works, thanks @alexeyten! I tested by uploading a php file onto the folder, and requested for it. Nginx serves it as a static file, which causes the browser to download it. That's the expected behaviour yes? – Honey Badger Mar 31 '14 at 8:37
  • 1
    Yes, that's default behavior. – Alexey Ten Mar 31 '14 at 8:39

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.