[Solved] Nginx cannot upload large files - 502 Gateway timeout

Submitted by sysop on Sat, 08/26/2023 - 07:32

[Solved] Nginx cannot upload large files - 502 Gateway timeout


 Nginx (pronounced "engine-x") is a high-performance, open-source web server and reverse proxy server software. It is designed to handle and efficiently serve static and dynamic content on the web. It is known for its scalability, speed, and ability to handle high levels of concurrent connections.
  1. Setup:We have the following setup. On front we have AWS ALB and on the backend we have nginx and php-fpm services running inside the containers. Also, on another container we have php container where we have drupal sites.
  2. Issue: We recently had an issue while uploading the large audio files to a Drupal site. Uploading the files upto 35MB worked but the size greater than that did not work.
  3. Things we tried: We tried to investigate the issue by setting higher upload, timeout and memory limits on both nginx and php-fpm configurations.
  4. Error we got: Nothing in nginx and php-fpm logs. But on the chrome console we got the below error.
    POST http://sitename/admin/add/test?element_parents=formfile&ajax_form=1&_wrapper_format=drupal_ajax&_wrapper_format=drupal_ajax HTTP/1.1" 400
  5. Nginx configurations we had:
        client_max_body_size 200M;
        client_body_buffer_size 200M;
        types_hash_max_size 2048;
        client_header_buffer_size 4k;
        large_client_header_buffers 4 16k;
        ## Needed for the PCI
        server_tokens off;
        ## This is for the configuration files. Nginx will tell you when it needs this increased.
        server_names_hash_bucket_size 512
  6. Troubleshooting:
    After wasting our time for 2 days, we were finally got the breakthrough. The culprit was the client_body_buffer_size setting. It was set to 200MB.
  7. Explanation:
    Basically, the buffer was too big and nginx was not able to allocate so much memory for keeping the file inside it. We had to lower the buffer to a normal value, so that file is buffered to a temp file during upload and things worked as expected from thereon.
  8. Conclusion:
    And thus "Nginx cannot upload large files - 502 Gateway timeout" was solved by setting the client_body_buffer_size value to 128K.

    Hope this documentation helps!!!!