Error request entity too large head банк оценщик

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


Linux, Программное обеспечение

  • 21.01.2015
  • 35 066
  • 5
  • 03.04.2020
  • 22
  • 21
  • 1

Исправляем ошибку: 413 Request Entity Too Large

  • Содержание статьи
    • Описание ошибки
    • nginx
    • Apache
      • httpd.conf
      • .htaccess
    • PHP
    • Комментарии к статье ( 5 шт )
    • Добавить комментарий

Описание ошибки

413 Request Entity Too Large

Данная ошибка может появиться в том случае, если вы загружаете какой-либо файл на сервер и размер этого файла превышает максимально разрешенный в конфиге в веб-сервера (например, в nginx по умолчанию установлено ограничение в 1 МБ).  Для того, чтобы это исправить, необходимо внести определенные правки в файл конфигурации, который может быть разным, в зависимости от используемого веб-сервера. Ниже будут приведены примеры для самых популярных веб-серверов:

nginx

Максимальный размер файла указывается параметром client_max_body_size. Поэтому, достаточно прописать параметр и новое значение в любой конфиг, который использует nginx для сайта, на котором у вас появилась эта проблема. Получится должно что-то примерно следующее:


server {
    ...
    client_max_body_size 4m;
    ...
}

Где 4m — это 4 Мб. Для установки лимита в 32 Мб, надо соответственно написать client_max_body_size 32m, и т. д.

После изменения настроек нужно обязательно перезагрузить конфиг в nginx.

Apache

httpd.conf

Размер файла, допустимого для заливки, можно отрегулировать в главном конфиге Apache, который можно найти по адресу /etc/httpd/conf/httpd.conf (в CentOS) или /etc/apache2/apache2.conf (в Debian/Ubuntu). Задается он параметром LimitRequestBody, и ему можно прописать любое нужное значение в байтах. Например, так выглядит ограничение в 32 МБ:

LimitRequestBody 33554432

Для применения настроек нужно перезагрузить веб-сервер Apache.

.htaccess

Очень часто у веб-сервера Apache для настройки определенного сайта используется файл .htaccess, который лежит в корневой директории веб-сайта. Удобство данного метода в том, что Вы можете прописать нужные настройки, которые будут применяться только для данной директории и веб-сайта, который данную директорию использует.

Если используемый для загрузки скрипт находится в какой-то поддиректории, где имеется свой файл .htaccess, то его настройки будут иметь больший приоритет!

Для этого, нужно либо открыть уже существующий файл .htaccess (или создать, в случае отсутствия) и добавить туда следующие строки (32 МБ в байтах):

LimitRequestBody 33554432

Если для работы сайта и заливки файла используется PHP, то нужно добавить еще другую строчку:

php_value upload_max_filesize 32M

PHP

Если при заливке файла используется PHP скрипт, то для PHP имеются отдельные настройки максимального размера файла. Для их изменений потребуется внести правку в файл php.ini, который расположен по адресу /etc/<версия php>/fpm. Открываем его любым текстовым редактором и находим следующие строки:

upload_max_filesize
post_max_size

И выставляем им нужные значения, например 4M (т. е. 4 МБ).

После внесения правок просто перезагружаем php, и проверяем работу.

Иногда при загрузке больших файлов на какой-либо веб-сайт может возникнуть ошибка, которую возвращает веб-сервер Nginx — 413 Request Entity Too Large. Данная ошибка появляется, при попытке загрузить на сервер слишком большой файл чем это разрешено на сервере.

В данной небольшой статье будет рассмотрено описание ошибки 413 Request Entity Too Large а также методы её исправления на стороне веб-сервера Nginx.

Ошибка 413 Request Entity Too Large дословно расшифровывается как объект запроса слишком велик или простыми словами объем передаваемых данных слишком большой. Данная ошибка возвращается в случае, если сервер не может обработать запрос по причине слишком большого размера тела запроса (или большого файла). Снимок экрана с ошибкой изображен ниже:

wP47iP96W9YvAAAAABJRU5ErkJggg==

По умолчанию в Nginx установлен лимит на размер тела запроса который равен 1 МБ. Если запрос превышает установленное значение, вы увидите ошибку 413 Request Entity Too Large.

Как исправить ошибку 413 Request Entity Too Large

Для того чтобы исправить данную ошибку необходимо увеличить допустимый лимит. Чтобы увеличить размер тела запроса и соответственно, загружаемых файлов, необходимо использовать параметр client_max_body_size. Данную опцию можно использовать в директивах http, server или location в конфигурационном файле /etc/nginx/nginx.conf или в конфигурационном файле веб-сайта.

Для этого необходимо открыть конфигурационный файл nginx.conf при помощи любого текстового редактора (например nano):

sudo nano /etc/nginx/nginx.conf

u5OMyOApCqZjMZNjHz4K0trEFvM5Pj+P8DzCrRn+soy7wAAAAASUVORK5CYII=

Далее впишите такую строчку в секцию http:

client_max_body_size 100M

Здесь 100 — это максимальный размер файла в мегабайтах который можно загрузить на веб-сайт, в данном случае — 100 мегабайт. Если в распоряжении имеется несколько веб-сайтов (серверные блоки в терминологии Nginx, они же виртуальные хосты в понимании другого веб-сервера — Apache) и необходимо чтобы ограничение на загрузку действовало на все сайты сразу, то строку client_max_body_size необходимо вписать в раздел блока http. Как было показано выше.

Если ограничение на загрузку необходимо выставить только для конкретного сайта, то строку client_max_body_size необходимо добавить в блок server конфигурационного файла сайта, который по умолчанию находиться в /etc/nginx/sites-available/имя_файла_с_конфигурацией:

8H6OBHbwZnuAcAAAAASUVORK5CYII=

Если ограничение на загрузку необходимо выставить только для конкретного раздела на сайте, строку client_max_body_size необходимо вписать в директиву location конфигурационного файла сайта, который по умолчанию находиться в /etc/nginx/sites-available/имя_файла_с_конфигурацией:

KxgCLvBCQMwAAAAASUVORK5CYII=

После внесения изменений в конфигурационные файлы необходимо сохранить изменения, закрыть текстовый редактор и проверить синтаксис конфигурационных файлов на наличие ошибок при помощи команды:

sudo nginx -t

j8OjMTx6bbbpAAAAABJRU5ErkJggg==

Если в выводе команды будут отображены следующие строки:

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

Это означает что ошибок нет. В противном случае будет выведено описание ошибки, имя файла в котором найдена ошибка и номер строки. После внесения любых изменений в конфигурационные файлы Nginx их необходимо перезапустить при помощи команды:

sudo systemctl reload nginx

Выводы

В данной короткой статье была рассмотрена ошибка в Nginx под названием 413 Request Entity Too Large которая возникает при загрузке больших файлов на веб-сайт. Помимо описания самой ошибки также было описаны шаги по устранению ошибки путем редактирования конфигурационных файлов Nginx.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Бывший системный администратор и DevOps инженер. Ныне работаю по направлению DevSecOps. Использую Linux более 5 лет. Помимо Linux интересую языком программирования Python, базами данных и языком SQL а также информационной безопасностью.

WordPress errors come in all shapes and sizes. In most cases they’re easy to decipher; such is the accessibility of WordPress’ error reporting. Even so, when the “413 Request Entity Too Large” error pops up, it can leave you scratching your head.

Without realizing it, you already have everything you need to understand and diagnose the error within its name. The good news is you won’t need more than a standard Secure File Transfer Protocol (SFTP) client and administrator access to your server.

In this post, we’ll take a look at how to solve the “413 Request Entity Too Large” error. We’ll also give you a quick list of steps to take before you begin to solve the error, to make the process super straightforward.

Check out our video guide to fixing the “413 Request Entity Too Large” Error

What the “413 Request Entity Too Large” Error Is (And Why It Exists)

We noted that there’s a clue in the error name as to what the solution and problem are. Before you go sleuthing yourself, though, we’ll spoil the surprise: it’s in the adjective “large.”

In a nutshell, the “413 Request Entity Too Large” error is a size issue. It happens when a client makes a request that’s too large for the end server to process. Depending on the nature of the error, the server could close the connection altogether to prevent further requests being made.

Let’s break the error down into its parts:

  • “413”: This is one of the 4xx error codes, which mean there’s a problem between the server and browser.
  • “Request Entity”: The “entity” in this case is the information payload being requested by the client from the server.
  • “Too Large”: This is straightforward: the entity is bigger than the server is willing or able to serve.

In fact, this error has changed its name from what it originally was to be more specific and offer more clarity. It’s now known as the “413 Payload Too Large” error, although in practice, you’ll see the older name a lot more.

As for why the error occurs, the simple explanation is that the server is set up to deny explicit uploads that are too large. Think of times when you upload a file where there’s a maximum file size limit:

The TinyPNG home page with the max upload of 5mb highlighted.

The TinyPNG home page.

In most cases, there will be some validation in place to stop the error… if you’re seeing the “413 Request Entity Too Large” error, those validation efforts may not be as watertight as you think.

What You’ll Need to Resolve the “413 Request Entity Too Large” Error

Fixing this error is all about raising the maximum file size for the server in question. Once that’s out of the way, you shouldn’t see the error anymore.

As such, to fix the “413 Request Entity Too Large” error, you’ll need the following:

  • Administrator access to your server.
  • A suitable SFTP client (we’ve covered many of these in the past).
  • The know-how to use SFTP — there’s a good guide to the basics on WordPress.org, and you won’t need more than that.
  • A text editor, though there’s no need for anything too complex.
  • A clean and current backup in case the worst happens.

As an aside, we mention SFTP throughout this article as opposed to FTP. In short, the former is more secure than the latter (hence the name). That said, while there are other differences you should investigate, the functionality remains the same for the vast majority of uses.

Also, it’s worth noting that the MyKinsta dashboard has plenty of functionality on hand to help you get onto your server. For example, each site displays SFTP connection information that’s easy to understand:

The SFTP panel in the MyKinsta dashboard.

The SFTP panel in the MyKinsta dashboard.

This can help you get into your site without fuss. In some cases, you may be able to import the credentials straight to your chosen SFTP client.

3 “Pre-Steps” You Can Take Before Rectifying the “413 Request Entity Too Large” Error

Before you crack open your toolbox, there are some steps you can take to help resolve the “413 Request Entity Too Large” error. Here are two — and each one may give you a welcome workaround to the error.

1. Try to Upload a Large File to Your Server Through SFTP

Because the issue is related to the file sizes hitting your server, it’s a good idea to circumvent the frontend interface and upload a large file to the server yourself. The best way to do this is through SFTP.

This is because protocols such as SFTP are almost as “close to the bone” as you can get with regards to the way you access your server. Also, you can simultaneously rule out any issues with the frontend that may be causing the error.

To do this, log into your site through SFTP and find the wp-content folder. In here will be the uploads folder.

The uploads folder seen from an SFTP client.

The uploads folder seen from an SFTP client.

Next, upload your file to this folder on the server and see what the outcome is. If the upload is successful, we suggest sending an email to the site’s developer, as they may want to investigate the issue further on the frontend.

2. Check for Server Permissions Errors

Of course, permissions errors will stop any server request from running. As such, you should check whether the user has sufficient permissions to upload files of any size. Once this is sorted, the error should disappear.

The first step is to determine whether this is an issue with a single user (in which case they may be restricted for a reason). If the “413 Request Entity Too Large” error is happening for multiple users, you can be more sure of something that needs your input.

We’d suggest two “pre-fixes” here:

  • Double-check your WordPress file permissions, just in case there’s an issue.
  • Remove and re-create your SFTP user (a general investigation is a great idea).

While they may not solve the error in the first instance, you’ll at least know that your file and user structure is as it should be.

How to Solve the “413 Request Entity Too Large Error” for Your WordPress Website (3 Ways)

Once you’ve gone through the pre-steps, you’re ready to tackle the error head-on.

The following three methods are listed from easiest to toughest, with the understanding that that the path of least resistance is the best one to take.

1. Edit Your WordPress functions.php File

First off, you can work with your functions.php file to help bump up the file upload size for your site. To do this, first log into your site through SFTP using the credentials found within your hosting control panel.

When you’re in, you’ll want to look for the file itself. The functions.php file should be in the root of your server. In many cases, this root is called www or public_html, or it could be the abbreviated name of your site.

Once you’ve found it, you can open it in your text editor of choice. If you don’t see the file, you can create it using your text editor.

Once you have a file open, enter the following:

@ini_set( '_max_size' , '64M' );
@ini_set( 'post_max_size', '64M');
@ini_set( 'max_execution_time', '300' );

In short, this increases the maximum file size of posts and uploads while boosting the time the server will spend trying to process the request. The numbers here could be anything you wish, but they should be large enough to make the error disappear. In practice, 64 MB is enough for all but the most heavy-duty of tasks.

The functions.php file.

The functions.php file.

When you’re ready, save your file and upload it to the server again. Then, check whether the “413 Request Entity Too Large” error still exists. If it does, head onto the next method.

2. Modify Your WordPress .htaccess File

Much like your functions.php file, your .htaccess file sits on your server. The difference here is that .htaccess is a configuration file for Apache servers. If you’re a Kinsta customer, you’ll know we run Nginx servers, so you won’t see this file in your setup.

Still, for those with an Apache server, this is the approach you’ll need. Much like with the guidance for functions.php, first log into your server through SFTP, then look in your root folder as before.

The .htaccess file should be within this directory, but if it’s missing, we suggest you get in touch with your host to determine where it is, and whether your server runs on Nginx instead.

Once you’ve found it, open it up again. You’ll see some tags, and the most important here is # END WordPress. You’ll want to paste the following after this line:

php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300

In short, this does almost the same thing as the code you’d add to the functions.php file, but it’s akin to giving the server direct instructions.

The .htaccess file.

The .htaccess file.

When you’ve finished, save your changes, upload the file, and check your site again. If you’re still having trouble, we’d again suggest contacting your host, as they will need to verify some aspects of your setup that lie beyond the scope of this article.

3. Change Your Nginx Server Configuration

Our final method is specific to Nginx servers — those used at Kinsta. The purpose is the same as when working with the .htaccess file, in that you’re talking to the server, rather than going through WordPress.

We mentioned that for Apache servers you’ll use .htaccess. For Nginx servers, though, you’ll want to find the nginx.conf file. Rather than walk you through every step in the chain, we’ve gone over the full details in our post on changing the WordPress maximum upload size.

Remember that you’ll need to also alter the php.ini file based on the changes you make to nginx.conf. We’ve covered that in the aforementioned blog post too, so take a look there for the exact steps.

Summary

Despite WordPress being a rock-solid platform, you’ll see a lot of different WordPress errors over time. The “413 Request Entity Too Large” error is related to your server, though — not WordPress. As such, there’s a different approach to solving this error than other platform-specific issues.

If you have SFTP skills, there’s no reason you can’t fix this error quickly. It relates to the upload size specified in your server configuration files, so digging into your .htaccess or nginx.config files will be necessary. It’s a breeze to crack open your text editor and make the changes to these files, and if you’re a Kinsta customer, we’re on hand to support you through the process.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

WordPress errors come in all shapes and sizes. In most cases they’re easy to decipher; such is the accessibility of WordPress’ error reporting. Even so, when the “413 Request Entity Too Large” error pops up, it can leave you scratching your head.

Without realizing it, you already have everything you need to understand and diagnose the error within its name. The good news is you won’t need more than a standard Secure File Transfer Protocol (SFTP) client and administrator access to your server.

In this post, we’ll take a look at how to solve the “413 Request Entity Too Large” error. We’ll also give you a quick list of steps to take before you begin to solve the error, to make the process super straightforward.

Check out our video guide to fixing the “413 Request Entity Too Large” Error

What the “413 Request Entity Too Large” Error Is (And Why It Exists)

We noted that there’s a clue in the error name as to what the solution and problem are. Before you go sleuthing yourself, though, we’ll spoil the surprise: it’s in the adjective “large.”

In a nutshell, the “413 Request Entity Too Large” error is a size issue. It happens when a client makes a request that’s too large for the end server to process. Depending on the nature of the error, the server could close the connection altogether to prevent further requests being made.

Let’s break the error down into its parts:

  • “413”: This is one of the 4xx error codes, which mean there’s a problem between the server and browser.
  • “Request Entity”: The “entity” in this case is the information payload being requested by the client from the server.
  • “Too Large”: This is straightforward: the entity is bigger than the server is willing or able to serve.

In fact, this error has changed its name from what it originally was to be more specific and offer more clarity. It’s now known as the “413 Payload Too Large” error, although in practice, you’ll see the older name a lot more.

As for why the error occurs, the simple explanation is that the server is set up to deny explicit uploads that are too large. Think of times when you upload a file where there’s a maximum file size limit:

The TinyPNG home page with the max upload of 5mb highlighted.

The TinyPNG home page.

In most cases, there will be some validation in place to stop the error… if you’re seeing the “413 Request Entity Too Large” error, those validation efforts may not be as watertight as you think.

What You’ll Need to Resolve the “413 Request Entity Too Large” Error

Fixing this error is all about raising the maximum file size for the server in question. Once that’s out of the way, you shouldn’t see the error anymore.

As such, to fix the “413 Request Entity Too Large” error, you’ll need the following:

  • Administrator access to your server.
  • A suitable SFTP client (we’ve covered many of these in the past).
  • The know-how to use SFTP — there’s a good guide to the basics on WordPress.org, and you won’t need more than that.
  • A text editor, though there’s no need for anything too complex.
  • A clean and current backup in case the worst happens.

As an aside, we mention SFTP throughout this article as opposed to FTP. In short, the former is more secure than the latter (hence the name). That said, while there are other differences you should investigate, the functionality remains the same for the vast majority of uses.

Also, it’s worth noting that the MyKinsta dashboard has plenty of functionality on hand to help you get onto your server. For example, each site displays SFTP connection information that’s easy to understand:

The SFTP panel in the MyKinsta dashboard.

The SFTP panel in the MyKinsta dashboard.

This can help you get into your site without fuss. In some cases, you may be able to import the credentials straight to your chosen SFTP client.

3 “Pre-Steps” You Can Take Before Rectifying the “413 Request Entity Too Large” Error

Before you crack open your toolbox, there are some steps you can take to help resolve the “413 Request Entity Too Large” error. Here are two — and each one may give you a welcome workaround to the error.

1. Try to Upload a Large File to Your Server Through SFTP

Because the issue is related to the file sizes hitting your server, it’s a good idea to circumvent the frontend interface and upload a large file to the server yourself. The best way to do this is through SFTP.

This is because protocols such as SFTP are almost as “close to the bone” as you can get with regards to the way you access your server. Also, you can simultaneously rule out any issues with the frontend that may be causing the error.

To do this, log into your site through SFTP and find the wp-content folder. In here will be the uploads folder.

The uploads folder seen from an SFTP client.

The uploads folder seen from an SFTP client.

Next, upload your file to this folder on the server and see what the outcome is. If the upload is successful, we suggest sending an email to the site’s developer, as they may want to investigate the issue further on the frontend.

2. Check for Server Permissions Errors

Of course, permissions errors will stop any server request from running. As such, you should check whether the user has sufficient permissions to upload files of any size. Once this is sorted, the error should disappear.

The first step is to determine whether this is an issue with a single user (in which case they may be restricted for a reason). If the “413 Request Entity Too Large” error is happening for multiple users, you can be more sure of something that needs your input.

We’d suggest two “pre-fixes” here:

  • Double-check your WordPress file permissions, just in case there’s an issue.
  • Remove and re-create your SFTP user (a general investigation is a great idea).

While they may not solve the error in the first instance, you’ll at least know that your file and user structure is as it should be.

How to Solve the “413 Request Entity Too Large Error” for Your WordPress Website (3 Ways)

Once you’ve gone through the pre-steps, you’re ready to tackle the error head-on.

The following three methods are listed from easiest to toughest, with the understanding that that the path of least resistance is the best one to take.

1. Edit Your WordPress functions.php File

First off, you can work with your functions.php file to help bump up the file upload size for your site. To do this, first log into your site through SFTP using the credentials found within your hosting control panel.

When you’re in, you’ll want to look for the file itself. The functions.php file should be in the root of your server. In many cases, this root is called www or public_html, or it could be the abbreviated name of your site.

Once you’ve found it, you can open it in your text editor of choice. If you don’t see the file, you can create it using your text editor.

Once you have a file open, enter the following:

@ini_set( '_max_size' , '64M' );
@ini_set( 'post_max_size', '64M');
@ini_set( 'max_execution_time', '300' );

In short, this increases the maximum file size of posts and uploads while boosting the time the server will spend trying to process the request. The numbers here could be anything you wish, but they should be large enough to make the error disappear. In practice, 64 MB is enough for all but the most heavy-duty of tasks.

The functions.php file.

The functions.php file.

When you’re ready, save your file and upload it to the server again. Then, check whether the “413 Request Entity Too Large” error still exists. If it does, head onto the next method.

2. Modify Your WordPress .htaccess File

Much like your functions.php file, your .htaccess file sits on your server. The difference here is that .htaccess is a configuration file for Apache servers. If you’re a Kinsta customer, you’ll know we run Nginx servers, so you won’t see this file in your setup.

Still, for those with an Apache server, this is the approach you’ll need. Much like with the guidance for functions.php, first log into your server through SFTP, then look in your root folder as before.

The .htaccess file should be within this directory, but if it’s missing, we suggest you get in touch with your host to determine where it is, and whether your server runs on Nginx instead.

Once you’ve found it, open it up again. You’ll see some tags, and the most important here is # END WordPress. You’ll want to paste the following after this line:

php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300

In short, this does almost the same thing as the code you’d add to the functions.php file, but it’s akin to giving the server direct instructions.

The .htaccess file.

The .htaccess file.

When you’ve finished, save your changes, upload the file, and check your site again. If you’re still having trouble, we’d again suggest contacting your host, as they will need to verify some aspects of your setup that lie beyond the scope of this article.

3. Change Your Nginx Server Configuration

Our final method is specific to Nginx servers — those used at Kinsta. The purpose is the same as when working with the .htaccess file, in that you’re talking to the server, rather than going through WordPress.

We mentioned that for Apache servers you’ll use .htaccess. For Nginx servers, though, you’ll want to find the nginx.conf file. Rather than walk you through every step in the chain, we’ve gone over the full details in our post on changing the WordPress maximum upload size.

Remember that you’ll need to also alter the php.ini file based on the changes you make to nginx.conf. We’ve covered that in the aforementioned blog post too, so take a look there for the exact steps.

Summary

Despite WordPress being a rock-solid platform, you’ll see a lot of different WordPress errors over time. The “413 Request Entity Too Large” error is related to your server, though — not WordPress. As such, there’s a different approach to solving this error than other platform-specific issues.

If you have SFTP skills, there’s no reason you can’t fix this error quickly. It relates to the upload size specified in your server configuration files, so digging into your .htaccess or nginx.config files will be necessary. It’s a breeze to crack open your text editor and make the changes to these files, and if you’re a Kinsta customer, we’re on hand to support you through the process.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Толстячок любит пожрать

При загрузке файла в свой блог, столкнулся с ошибкой «413 Request Entity Too Large». Быстрое гугление показало, что для исправления, нужно чуть поднастроить веб-сервер..

Что означает ошибка «413 Request Entity Too Large»

Ошибка «413 Request Entity Too Large» переводится как «Размер запроса слишком большой» возникает когда размер запроса от клиента превышает максимальные ограничения установленные для обработки на стороне веб-сервера. Такие ограничение применяют для защиты от атак направленных на увеличение нагрузки на веб-сервер.

Например, в моем случае, я попытался загрузить gif-ку размер которой был около 2 мб. Соответственно мой браузер отправил POST запрос на веб-сервер, примерно такого же размера. В результате я получил ошибку «Request entity too large» от веб-сервера, о том, что мой запрос слишком большой для дальнейшей обработки.

Как исправить ошибку «413 Request Entity Too Large» со стороны клиента

Самый простой способ, это уменьшить размер запроса. Тут многое зависит от того, что именно вы отправляете на сервер.

Если это форма с несколькими файлами, попробуйте загружать файлы по одному.

Если это какие-то документы и есть возможность, попробуйте их заархивировать.

Если это картинка, попробуйте её сохранить в другом формате, например уменьшить разрешение и сохранить в JPG.

У Вас Jpeg

У Вас Jpeg

Как исправить ошибку «413 Request Entity Too Large» на стороне Nginx веб-сервера

Разумеется, можно поправить конфигурацию веб-сервера, если у вас есть к ней доступ, чтобы избежать таких ошибок в дальнейшем.

В nginx, за это отвечает опция client_max_body_size: http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size
Значение по-умолчанию: 1Мб

Данную опцию можно использовать в следующих контекстах: http, server, location. Т.е. можно задать глобальное значение, значение для домена и значение для конкретного адреса url.

Я решил увеличить глобальное значение, т.к. это исправит проблему сразу для нескольких блогов, расположенных в рамках одного сервера.

Для этого добавляем нужное значение (в моем случае это 16 Мб) в главный файл конфигурации

$ sudo nano /etc/nginx/nginx.conf

...

http {

    ...

    client_max_body_size 16M;

    ....

}

далее, проверяем конфигурацию и перезапускаем nginx

$ sudo nginx t

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

nginx: configuration file /etc/nginx/nginx.conf test is successful

$ sudo nginx s reload

Пример конфигурации в других контекстах

server {

    client_max_body_size 1m;

    location /users/profile/edit/avatar {

        client_max_body_size 2m;

        ...

    }

    location /users/profile/edit/images {

        client_max_body_size 5m;

        ...

    }

}

Как исправить ошибку «413 Request Entity Too Large» на стороне Apache веб-сервера

В Apache эта опция называется LimitRequestBody: http://httpd.apache.org/docs/2.4/mod/core.html#LimitRequestBody
По-умолчанию лимит не установлен (равен 0). Размер задается в байтах

Данную опцию можно использовать в следующих контекстах: server config, virtual host, directory, .htaccess. Т.е. можно задать глобальное значение, значение для домена, значение для конкретного url, а так же модифицировать его через .htaccess

Пример конфигурации VirtualHost

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<VirtualHost *:80>

    # Small, safe default (1 MB)

    <Location />

        LimitRequestBody 1048576

    </Location>

    # 2 MB

    <Location /users/profile/edit/avatar>

        LimitRequestBody 2097152

    </Location>

    # 5 MB

    <Location /users/profile/edit/images>

        LimitRequestBody 5242880

    </Location>

</VirtualHost>

Пример изменения конфигурации в .htaccess

$ nano .htaccess

...

LimitRequestBody 5242880

...

Заключение

В современном мире знать и уметь все не возможно. Для решения повседневных проблем самое главное умение — это уметь искать нужную информацию в интернете. Если Вы это читаете, то у Вас все хорошо 🙂

Уметь гуглить полезно

Понравилась статья? Поделить с друзьями:
  • Error resource conflict pci on motherboard
  • Error resource alloc failed reason 8007000e
  • Error repository not found git clone
  • Error repository not found fatal could not read from remote repository
  • Error resolving pool 0 ubuntu pool ntp org name or service not known 2