Nginx php file upload size

Configuring Nginx and PHP 7 stack in Linux to increase or decrease file upload size limit

PHP web applications can utilize Nginx as the reverse proxy server and PHP FPM as the upstream server. Whenever you encounter HTTP file upload issues, limitation in file upload size is one common cause.

This post shows how to adjust the file upload size limit for your application running on a Nginx-PHP stack in Linux.

Читайте также:  Программирование линейных алгоритмов 8 класс python

Two sets of file upload size limit configuration to apply for Nginx-PHP LEMP stacks

The following digram is an illustration of how the browser communicates with the application server in a typical LEMP stack.

As shown above, there are two machines that process HTTP requests received from HTTP clients. Therefore, we need to apply two sets of file upload size limit configuration — one for Nginx and the other for the PHP-FPM server.

Configuring file upload size limit for Nginx

Firstly, let’s look at how we can configure file upload size limit for Nginx.

Locating the Nginx configuration file

A typical installation of Nginx associates the nginx binary with the PATH variable. Therefore, you can locate the Nginx configuration file by running the following command in your terminal program:

When I run this on my Raspberry Pi 3 running Codiad Web IDE, I got the following output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

As can be seen, nginx reported that it is taking configurations from /etc/nginx/nginx.conf . Given that, we know where to look at for adjusting the file upload size limit for Nginx.

Configuring the file upload size limit for Nginx via client_max_body_size directive

Once you had figured out the location of the configuration file that you wish to edit, you can then proceed to add in the client_max_body_size directive with a value that you desire.

This directive defines the maximum allowed size of client request body. In addition, the default value is 1 Megabyte. When we set a value of 0 , we disable the checking of the client request body size.

Since a file is included as the client request body, we will adjust the file upload size via the client_max_body_size directive.

Universal file upload size limit for HTTP requests made to all upstream servers

In case you want to allow a file smaller than 8 Megabytes to get through your Nginx server for all upstream servers, you will apply the client_max_body_size directive inside the http block:

Site specific file upload size limit

In case you want to apply another file upload size limit for HTTP request made to a specific upstream server, you need to look for the server block for that site. For example, the following configuration allows any file smaller than 1 Gigabytes to pass Nginx for my Raspberry Pi 3 file sharing website:

Uri specific file upload size limit

You can also apply the file upload size limit to a specific Uri. For example, the following configuration will apply a file upload size limit of 2 Gigabytes for HTTP requests sent to http://www.adomain.com/upload:

Configuring file upload size limit for PHP FPM 7

Lastly, let’s look at how to configure file upload size limit for PHP FPM 7.

Locating the php.ini configuration file

Before you proceed to configure the file upload size limit for PHP FPM 7, you need to find the php.ini configuration file. In general, you can run the following command to look for php.ini :

After the command completes, you may find output similar to the following in your terminal screen:

/etc/php/7.0/fpm/php.ini /etc/php/7.0/cli/php.ini

In this case, we will edit /etc/php/7.0/fpm/php.ini to configure the file upload size limit for PHP FPM 7.

Configuring file upload size limit for PHP FPM 7 via upload_max_filesize and post_max_size

In order to change file upload size limit for PHP, we need to change two settings — upload_max_filesize and post_max_size .

The default value for upload_max_filesize is 2 Megabytes.

The default value for post_max_size is 8 Megabytes.

Note that the post_max_size has to be larger than upload_max_filesize for large files.

In addition to those two variables, you may want to set max_input_time to a higher value for large files. In this case, your clients will be given more time to upload files to your PHP FPM 7 server.

Universal file upload size limit for HTTP requests made to all PHP applications served by PHP FPM 7

To apply a common file upload size limit for all PHP applications served by PHP FPM 7, you will edit the values for upload_max_filesize and post_max_size from /etc/php/7.0/fpm/php.ini .

For example, if we want to change the file upload size limit to 200 Megabytes, we will first open up /etc/php/7.0/fpm/php.ini . After the editor loads the file, we will then change the lines with upload_max_filesize and post_max_size variables to the following:

upload_max_filesize = 200M post_max_size = 202M

Application specific file upload size limit

To adjust the file upload size limit for different PHP applications served by PHP FPM 7, we can do so via the ini_set function.

For example, if we want to change the file upload size limit to 300 Megabytes, we will include the following PHP codes in a running script:

@ini_set( 'upload_max_size' , '300M' ); @ini_set( 'post_max_size', '302M');

Restarting Nginx and PHP FPM 7 for the new file upload size limit to take effect

Once you had included the new file upload size limit for your Nginx server and PHP FPM server, restart them:

sudo systemctl restart php7.0-fpm.service sudo systemctl restart nginx.service

After your Nginx server and PHP FPM server had restarted, the new file upload size limit will take effect.

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.

Источник

How to Limit File Upload Size in Nginx

In our last article, we’ve explained about limiting user file upload size in Apache. In this article, we will explain how to limit user file upload size in Nginx. Restricting file upload size is useful to prevent some types of denial-of-service (DOS) attacks and many other related issues.

By default, Nginx has a limit of 1MB on file uploads. To set file upload size, you can use the client_max_body_size directive, which is part of Nginx’s ngx_http_core_module module. This directive can be set in the http, server or location context.

It sets the maximum allowed size of the client request body, specified in the “Content-Length” request header field. Here’s an example of increasing the limit to 100MB in /etc/nginx/nginx.conf file.

Set in http block which affects all server blocks (virtual hosts).

Set in server block, which affects a particular site/app.

Set in location block, which affects a particular directory (uploads) under a site/app.

Save the file and restart Nginx web server to apply the recent changes using following command.

# systemctl restart nginx #systemd # service nginx restart #sysvinit

Once you have saved the changes and restarted the HTTP server, if the size in a request exceeds the configured value of 100MB, the 413 (Request Entity Too Large) error is returned to the client.

Note: You should keep in mind that sometimes browsers may not correctly display this error. And setting a valua (size) to 0 disables checking of client request body size.

You might also like to read these following articles related to Nginx web server administration.

That’s all! In this short article, we have explained how to limit user file upload size in Nginx. You can share your thoughts with us via the comment form below.

Источник

Increase file upload size limit in PHP-Nginx

If Nginx aborts your connection when uploading large files, you will see something like below in Nginx’s error logs:

[error] 25556#0: *52 client intended to send too large body:

This means, you need to increase PHP file-upload size limit. Following steps given below will help you troubleshoot this!

Changes in php.ini

To change max file upload size to 100MB

upload_max_filesize = 100M post_max_size = 100M

Notes:

  1. Technically, post_max_size should always be larger than upload_max_filesize but for large numbers like 100M you can safely make them equal.
  2. There is another variable max_input_time which can limit upload size but I have never seen it creating any issue. If your application supports uploads of file-size in GBs, you may need to adjust it accordingly. I am using PHP-FPM behind Nginx from very long time and I think in such kind of setup, its Nginx to which a client uploads file and then Nginx copies it to PHP. As Nginx to PHP copying will be local operation max_input_time may never create issue. I also believe Nginx may not copy the file but merely hand-over the location of file or descriptor records to PHP!

Change in Nginx config

Add following line to http block in nginx config:

Note: For very large files, you may need to change value of client_body_timeout parameter. Default is 60s.

Reload PHP-FPM & Nginx

service php5-fpm reload service nginx reload

Changes in WordPress-Multisite

If you are running WordPress Multisite setup, then you may need to make one more change at the WordPress end.

Go to: Network Admin Dashboard >> Settings. Look for Upload Settings

Also change value for Max upload file size

More…

Источник

Разрешаем загрузку больших файлов в nginx/apache/php

Директива client_max_body_size задаёт максимально допустимый размер тела запроса клиента, указываемый в строке «Content-Length» в заголовке запроса. Если размер больше заданного, то клиенту возвращается ошибка «Request Entity Too Large» (413). Следует иметь в виду, что браузеры не умеют корректно показывать эту ошибку.

sudo nano /etc/nginx/nginx.conf

Далее находим или вставляем в секцию http следующую строчку:

client_max_body_size 100m;

После чего нужно будет не забыть перезагрузить nginx:

sudo service nginx reload

Apache/Php

Нужно изменить в php.ini сервера максимально разрешенный объём загружаемых файлов на нужное значение и перезагрузить apache. Это параметры upload_max_filesize и post_max_size.
sudo nano /etc/php/8.1/apache2/php.ini

Находим и изменяем следующую директиву:

Сохраняем файл и перезагружаем apache:

sudo service apache2 reload

Nginx: timeout

Бывает такое, что загружаешь большой файл, а сайт отваливается по таймауту:

504 Gateway Time-out
nginx

Довольно неприятная ситуация. Ты сидишь и думаешь, а загрузился ли твой файл или нужно заново грузить. Так вот, есть и под это директива в nginx

sudo nano /etc/nginx/sites-available/yourdomain.ru

Добавляем/изменяем в секции location / <> следующие строчки (время в секундах):

location / . 
proxy_connect_timeout 500;
proxy_send_timeout 500;
proxy_read_timeout 500;
.
>

Я указал 500 секунд, нужно понимать, что это фантастическая величина и она вам явно не нужна на сервере, но, вы можете поставить её на своё усмотрение!

Рубрики

При заказе по этой ссылке бесплатно помогу настроить и подготовить сервер к повседневной эксплуатации.

Источник

Оцените статью