SoFunction
Updated on 2025-04-08

Implementation example of nginx file upload and download control

Upload size control

client_max_body_size

Set the maximum client request size

The default size is 1M, which can be used in http, server, location blocks.

Set different size controls according to different request paths

server {
	listen    9001;
	client_max_body_size 2M;
	location / {
		root D:\\server\\nginx-1.22.0\\html\\9001;
	}
	
	location /upload/large {
        # Set a 50MB limit for large file upload paths        client_max_body_size 50M;
    }
	
	location /upload/small {
        # Set a 10MB limit for small file upload path        client_max_body_size 10M;
    }
}

Download control

Download speed control
limit_rate $rate

Limit file download speed, the default value is limit_rate 0; no download speed control is performed. $rate is used to specify the amount of data that can be downloaded per second.

The scope of the limit_rate directive can be http, server, location, if in location.

Restrict file downloads

server {
	listen    9001;
	limit_rate 100k;
	location / {
		root html;
	}	
}

Downloading files under this server will limit the download speed to 100kb per second.

limit_rate_after

The limit_rate_after instruction can set the limit download speed after a certain amount of data is transferred. It is usually used to limit subsequent download speeds when a file has started downloading.

	location /download {
		root html;
		limit_rate_after 2M;
		limit_rate       100k;
	}

The above configuration is to start speed limit after 2M download, which is 100kb per second.

Control download speed in different conditions

If you want to control the download speed based on different conditions (such as the requested file type, client IP, or the requested file size, etc.), you can combine map instructions and limit_rate to implement more complex logic.

http {
    map $http_user_agent $download_speed {
        default 100k;          # Default speed limit 100KB/s        ~*Chrome 300k;        # For Chrome browser, download speed limit is 300KB/s        ~*Firefox 200k;        # For Firefox browsers, download speed limit is 200KB/s    }

    server {
        listen 9001;

        location /donload/ {
            # Dynamically set download speed using map            limit_rate $download_speed;
            
            root html;
        }
    }
}

This is the article about the implementation example of nginx file upload and download control. For more related nginx file upload and download content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!