How to Fix the bug of File Size Limits in Web Applications: it works well in the local environment but not on AWS EC2

Henry Wu
bugfixed
Published in
3 min readFeb 23, 2024

I encountered a bug in the process of file size limitation. What I want is if the file the user uploads is larger than 5MB, then pop up an alert. It works well on my local environment, but after I deploy it on AWS EC2, it doesn’t work.

After a few hours of asking ChatGPT and testing, I found the reason: the AWS EC2 environment (Web server/Nginx/Apache) has a default file size limit for uploads.

Specifically, the default client_max_body_size in Nginx, which might be used as a reverse proxy or web server on an AWS EC2 instance, is 1 MB (megabyte). This means that by default, Nginx will reject any request with a body size larger than 1 MB, returning a 413 Request Entity Too Large error response.

Adjusting Nginx’s client_max_body_size on AWS EC2

ssh -i /path/to/your-key.pem ec2-user@your-instance-ip
sudo nano /etc/nginx/nginx.conf

If client_max_body_size is not set here or you need to set it for a specific site, look for the included site configuration files. If you're using the default server block or a specific site configuration, it might be in /etc/nginx/sites-available/ or /etc/nginx/conf.d/.

sudo nano /etc/nginx/nginx.conf
http {
client_max_body_size 5M;
}

Save the Configuration and Exit the Editor:

After adding or modifying the directive, save the file and exit the editor. If using nano, you can press Ctrl + X to exit, press Y to save changes, and then press Enter to confirm.

sudo nginx -t

sudo systemctl reload nginx

sudo service nginx reload

A Client-Side Alternative: JavaScript Validation

An alternative approach involves implementing client-side validation with JavaScript. This method provides immediate feedback to users attempting to upload files that exceed the size limit, enhancing the user experience and reducing unnecessary server load.


fileInput.addEventListener('change', function() {
if (this.files && this.files[0]) {
const file = this.files[0];

// Define your file size limit (e.g., 5 MB)
const maxSize = 5 * 1024 * 1024; // 5 MB in bytes

// Check if the file size exceeds the maximum size
if (file.size > maxSize) {
// Inform the user and prevent the upload
alert('Oh no. File size exceeds limit, please upload a smaller file.', false);
// Optionally, clear the file input
this.value = '';
return; // Exit the function to avoid proceeding with the upload
}

--

--

Henry Wu
bugfixed

Indie Developer/ Business Analyst/ Python/ AI/ Former Journalist/ Codewriter & Copywriter