How To: Fix 413 errors for apps behind nginx on AWS Elastic Beanstalk

So you've added a file uploader to your app. Everything is running beautifully on your local environment, passes all your tests, and it's time to push to production. You press the big red deploy button and then, with a smile on your face you try to upload a file and crack open a cold beer to celebrate.

But... what's this? A 413 error? But it was working on local and now your beer is getting warm! What should you do?

413 (Request Entity Too Large) errors are fortunately pretty easy to fix and pretty easy to understand. In a nutshell, the file you are sending is too large and nginx will not accept it.

Before diving into the fix, let's talk about nginx for a second. Nginx is a reverse proxy, meaning it sits between incoming web requests and your web application. It performs a number of useful tasks for you that you probably take for granted, however in this case one of those tasks is getting the way of your file upload feature. By default nginx is configured to make sure that large data transfer requests are not being fired at your application over and over again.

But, in some cases (like when you are uploading a file), this configuration is not necessary and hinders your progress. So all you need to do is configure nginx so that it will allow these requests to come through.

The simplest way to do this is to locate your nginx configuration file and then paste in the following somewhere within the http, server, or location contexts:

client_max_body_size 2M;

But you wanted your app to scale! So you built it on AWS Elastic Beanstalk. It was a good choice, but it's going to require another step to update your nginx configuration. In order to get the nginx configuration to stick, you need to do the following:

  • In your .ebextensions folder, create a file called 01_files.config (replace 01 with the sequential number that matches your project)
  • Paste the fillowing code into the file:
    "/etc/nginx/conf.d/proxy.conf" :
        mode: "000755"
        owner: root
        group: root
        content: |
           client_max_body_size 20M;

Now deploy your app like you normally would. Your app will be restarted and your client_max_body_size will be increased to 20MB. You can adjust this filesize however you want, but 20MB is good for most applications. Also, you can add additional nginx settings to the content section, this may be helpful the next time you get an unexpected error in production only.

And thats it. Now, finally, you can crack your beer open and celebrate your new features! I hope this was helpful & happy coding!

So let's do this.

Try Zigpoll and get the most out of your visitors.

Questions or Feedback?

We would love to hear from you.