NGINX Directive – Fixing NGINX client_max_body_size Directive Inside Location Block

nginx

I have an /admin catalog on my website and I would like to allow admins to upload large files via web forms. Here is how my nginx.com looks:

http {
    # ...
    client_max_body_size 16M;
    # ...

    server {
        server_name example.com;
        root /var/www/example.com;
        index index.php;

        location /admin {
            client_max_body_size 256M;
        }

        # ...
    }
}

This does not work. /admin/index.php script cannot upload files larger that 16Mb: 413 Request Entity Too Large

However, if I move client_max_body_size to server block everything works fine. But I wouldn't want to make this change only for admin catalog.

According to docs, client_max_body_size can be placed inside location block to override setting only for desired path.

What could be wrong?

Best Answer

It works just fine, the problem is you have misunderstood how locations work. Nginx will only ever apply one location block, never more than one. So when you have two locations

location ~ \.php$ and location /admin and the URI is /admin/index.php then your first location applies but the second one doesn't. Even if you were to use a rewrite within a location then nginx would discard directives and reparse them for the new location.

This is also the reason why you always post full configs so that you don't hide what's actually wrong.