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




... 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!


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. 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? 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 agree to our terms of service, privacy policy and cookie policy

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