Ritu Aggrawal

ritu_aggrawal

Site reliability engineer at Uber Updated March 8, 2020, 11:17 a.m. ⋅ 36 views

How to limit file upload size on Ngnix


At some point we need to allow user to upload some content, for example any image, pdf, xlsx etc. on our website. To keep a control on size of uploaded file, we need to limit it. Otherwise it can be abused to break the server. In this article, I will explain how to limit user file upload size in Nginx. Restricting file upload size is useful to prevent some types of denial-of-service (DOS) attacks and many other related issues. Also, it's a good idea to limit via Ngnix tha via backend script, because in order to make backend script verify file size first file needs to be uploaded. Once file is uploaded there is no point checking because anyone can upload a file of 1 TB and abuse your system.

 

By default, Nginx has a limit of 1MB on file uploads. 

client_max_body_size directive is used to set file upload size.

 It is part of Nginx’s ngx_http_core_module module.

We can set this directive in the http, server or location context.

I'll try to set file upload limit to 10 MB in this article. Let's first open up the Ngnix's conf file.

sudo vim /etc/nginx/nginx.conf

 

If you are hosting multiple sites using virtual host, and want to set upload limit for all the sites then add client_max_body_size in http block. Like this:

 

http {
    ...
    client_max_body_size 10M;
}  

 

If you want to set upload limit for any specific website among virtual hosts, you can set client_max_body_size in server block of that site. Like this:

server {
    ...
    client_max_body_size 10M;
}

 

If you want to set limit of a specifi directory on you website, you do that this way:

location /uploads {
    ...
    client_max_body_size 10M;
}

This will set limit for /uploads directory to 10MB.

 

After this you need to restart Ngnix.

sudo systemctl restart nginx
sudo service nginx restart

 

From now onwards,  if the size in a request exceeds the configured value of 10MB, the 413 (Request Entity Too Large) error is returned to the client. Sometimes browsers may not correctly display this error. And setting a value (size) to 0 disables checking of client request body size.



arrow_upward Upvote

comment Comment

arrow_downward downvote



Go back to feed

HackersFriend Updates





View more


Events


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details


Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details