4

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!

Honey Badger
  • 829
  • 3
  • 11
  • 15

1 Answers1

9

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.

Alexey Ten
  • 8,435
  • 1
  • 34
  • 36
  • 1
    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 08:20
  • 3
    It doesn't matter. Nginx checks prefix locations before regexp's ones. – Alexey Ten Mar 31 '14 at 08: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 08:37
  • 1
    Yes, that's default behavior. – Alexey Ten Mar 31 '14 at 08:39