Access error request entity too large

Как исправить ошибку сервера 413 Request Entity Too Large - пошаговая инструкция и самые эффективные способы устранения ошибки. Эта HTTP-ошибка говорит об отправке слишком большого запроса на сервер.

Ошибка HTTP 413 Request Entity Too Large появляется, когда пользователь пытается загрузить на сервер слишком большой файл. Размер определяется относительно лимита, который установлен в конфигурации. Изменить его может только администратор сервера. 

Что делать, если вы пользователь

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

  • Если вы пытались загрузить одновременно несколько файлов (форма позволяет так делать), попробуйте загружать их по одному.
  • Если не загружается изображение, уменьшите его размер перед загрузкой на сервер. Можно сделать это с помощью онлайн-сервисов — например, Tiny PNG.
  • Если не загружается видео, попробуйте сохранить его в другом формате и уменьшить размер. Можно сделать это с помощью онлайн-сервисов — я использую Video Converter.
  • Если не загружается PDF-документ, уменьшите его размер. Можно сделать это с помощью онлайн-сервисов — я обычно использую PDF.io.

Универсальный вариант — архивация файла со сжатием. Ошибка сервера 413 появляется только в том случае, если вы пытаетесь одновременно загрузить слишком большой объем данных. Поэтому и выход во всех ситуациях один — уменьшить размер файлов.

Ошибка 413

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Исправление ошибки сервера 413 владельцем сайта

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

Чтобы понять, что стало причиной ошибки, нужно посмотреть логи. Это поможет сэкономить время. Вот подробная инструкция, которая рассказывает, как посмотреть логи в панели управления Timeweb. В зависимости от того, какая информация будет в логах, вы поймете, как исправлять ошибку 413.

Увеличение разрешенного размера для загрузки файлов на Nginx и Apache

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

Параметр client_max_body_size находится в файле nginx.conf. Для его изменения нужен текстовый редактор — например, vi.

Подключитесь к серверу через SSH и выполните в консоли следующую команду:

Во встроенном редакторе vi откроется файл nginx.conf. В разделе http добавьте или измените следующую строку:

client_max_body_size 20M;

Сохраните и закройте файл. Затем проверьте конфигурацию файла:

Перезагрузите сервер следующей командой:

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

На Apache опция, устанавливающая максимально допустимый размер загружаемого файла, называется LimitRequestBody. По умолчанию лимит не установлен (равен 0). 

На CentOS главный конфиг располагается по адресу /etc/httpd/conf/httpd.conf. На Debian/Ubuntu — по адресу /etc/apache2/apache2.conf

Значение задается в байтах:

LimitRequestBody 33554432

Эта запись выставляет максимально допустимый размер 32 МБ.

Изменить конфиги можно также через панель управления. Я пользуюсь ISPmanager, поэтому покажу на ее примере.

  1. Раскройте раздел «Домены» и перейдите на вкладку «WWW-домены».
  2. Выберите домен, на котором появляется ошибка, и нажмите на кнопку «Конфиг».

Apache и Nginx конфиги

Появится вкладка с конфигами Apache и Nginx. Вы можете редактировать их вручную, устанавливая лимит на размер загружаемого файла.

Исправление ошибки на WordPress

На WordPress ошибку можно исправить двумя способами.

Способ первый — изменение разрешенного размера в файле functions.php. Этот файл отвечает за добавление функций и возможностей — например, меню навигации.

  1. Откройте файловый менеджер.
  2. Перейдите в папку public.html.
  3. Откройте директорию wp-content/themes.
  4. Выберите тему, которая используется на сайте с WordPress.
  5. Скачайте файл functions.php и откройте его через любой текстовый редактор.

В панели управления на Timeweb можно также воспользоваться встроенным редактором или IDE — путь будет такой же, как указан выше: public.html/wp-content/themes/ваша тема/functions.php

В конце файла functions.php добавьте следующий код: 

@ini_set( 'upload_max_size' , '256M' );

@ini_set( 'post_max_size', '256M');

@ini_set( 'max_execution_time', '300' );

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

Редактирование файла functions.php

Второй способ — изменение файла .htaccess. Это элемент конфигурации, который способен переопределять конфигурацию сервера в плане авторизации, кэширования и даже оптимизации. Найти его можно через файловый менеджер в папке public.html.

Скачайте файл на компьютер, на всякий случай сделайте резервную копию. Затем откройте .htaccess в текстовом редакторе и после строчки #END WORDPRESS вставьте следующий код:

php_value upload_max_filesize 999M

php_value post_max_size 999M

php_value max_execution_time 1600

php_value max_input_time 1600

Сохраните файл и загрузите его обратно на сервер с заменой исходного файла. То же самое можно сделать через встроенный редактор или IDE в панели управления Timeweb.

Исправление ошибки при использовании PHP-скрипта

Если файлы загружаются с помощью PHP-скрипта, то для исправления ошибки 413 нужно отредактировать файл php.ini. В нем нас интересуют три директивы.:

  • upload_max_filesize — в ней указан максимально допустимый размер загружаемого файла (значение в мегабайтах);
  • post_max_size — максимально допустимый размер данных, отправляемых методом POST (значение в мегабайтах);
  • max_execution_time — максимально допустимое время выполнения скрипта (значение в секундах).

Например, если я хочу, чтобы пользователи могли загружать файлы размером до 20 МБ, то я делаю так:

max_execution_time = 90

post_max_size = 20M

upload_max_filesize = 20M

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

То же самое можно сделать через панель управления. Например, в ISPmanager порядок будет такой:

  1. Авторизуйтесь с root-правами.
  2. В левом меню раскройте раздел «Настройки web-сервера» и перейдите на вкладку «PHP».
  3. Выберите используемую версию и нажмите на кнопку «Изменить».

Изменение конфигурации PHP

На экране появится список параметров. Они отсортированы по алфавиту. Установите необходимые значения для параметров max_execution_time, post_max_size и upload_max_filesize. Изменения применяются автоматически.

VDS Timeweb арендовать

I had the same issue but in docker. when I faced this issue, added client_max_body_size 120M; to my Nginx server configuration,

nginx default configuration file path is /etc/nginx/conf.d/default.conf

server {
    client_max_body_size 120M;
    ...

it resizes max body size to 120 megabytes. pay attention to where you put client_max_body_size, because it effects on its scope. for example if you put client_max_body_size in a location scope, only the location scope will be effected with.

after that, I did add these three lines to my PHP docker file

RUN echo "max_file_uploads=100" >> /usr/local/etc/php/conf.d/docker-php-ext-max_file_uploads.ini
RUN echo "post_max_size=120M" >> /usr/local/etc/php/conf.d/docker-php-ext-post_max_size.ini
RUN echo "upload_max_filesize=120M" >> /usr/local/etc/php/conf.d/docker-php-ext-upload_max_filesize.ini

since docker PHP image automatically includes all setting files from the path (/usr/local/etc/php/conf.d/) into php.ini file, PHP configuration file will change by these three lines and the issue must disappear

When building and maintaining a website, you’re bound to encounter some unexpected HTTP errors here and there. Problems like these are tough to avoid, and some are trickier to resolve than others.

two people using a laptop computer to resolve a 413 request entity too large error

If you’re experiencing a «413 Request Entity Too Large» error, the good news is that this issue is quick and simple to address — you just need to do a bit of server reconfiguration. And no, you don’t need to be a technical expert. Let’s learn how.

Free Resource: Website Optimization Checklist [Download Now]

A 413 HTTP error code occurs when the size of a client’s request exceeds the server’s file size limit. This typically happens when a client attempts to upload a large file to a web server, and the server responds with a 413 error to alert the client.

Web servers place size limits on uploads to prevent users from overwhelming the server and exceeding storage permissions. This limit usually isn’t an issue, and common website files should stay well under it. However, especially large file uploads may occasionally exceed the limit, resulting in a message like this:

a 413 request entity too large error in a browser window

While you can reduce the size of your upload to get around the error, it’s also possible to change your file size limit with some server-side modification.

How to Fix a “413 Request Entity Too Large” Error

Your default upload size limit will depend on how your server is set up. In this guide, we’ll show you how to fix a 413 error by increasing your size limit with a WordPress setup, as well as with an Apache or Nginx server configuration.

All methods require some edits to your server files, so we recommend creating a backup before attempting the steps below.

WordPress

Themes and plugins are common causes of the 413 error with the WordPress content management system. Fortunately, there are several ways to increase your WordPress upload size limit enough to let these larger files through. As long as you do not exceed the limits of your hosting plan, you can try any of the following:

Modify PHP.ini

The easiest method to increase your upload limit is by modifying your server’s PHP.ini file. Here, you can change your limit through the cPanel interface without any coding. To do this:

1. In your cPanel menu, select MultiPHP INI Editor under Software.

how to fix request entity too large: software section in cpanel

2. In the window that appears, choose your domain from the dropdown menu.

3. Change the values of the following parameters to your preference:

  • max_execution_time (maximum time to upload, in seconds)
  • upload_max_filesize (maximum upload size, in megabytes)
  • post_max_size (maximum post size, in megabytes)

4. When finished, click Apply.

Modify .htaccess

If your WordPress site is hosted on an Apache server, it’s also possible to increase your server’s limit via .htaccess, a file that contains many directives for the server. See the solution below.

Modify functions.php

You can also try increasing your size limit via the functions.php file of your current WordPress theme.

If you want to make this change permanent, we recommend trying the above approaches first. With this approach, you’ll need to update functions.php whenever you update or change your current theme.

1. In your cPanel menu, select File Manager under Files.

how to fix request entity too large: files section in cpanel

2. Navigate to the folder of your current theme inside your root WordPress directory (public_html by default). Open this theme file.

3. Select functions.php and click the Edit icon.

4. Copy the code below and paste it at the end of the file

 
@ini_set( ‘upload_max_size’ , ’64M’ );
@ini_set( ‘post_max_size’, ’64M’);
@ini_set( ‘max_execution_time’, ‘300’ );

5. Click Save.

This code sets the maximum allowed size of your WordPress uploads and posts to 64 megabytes. You can change this number to something larger or smaller if you need, as long as you do not exceed your hosting plan’s storage limit.

It also sets the maximum period your uploads can take to 300 seconds. Feel free to change this as well.

Nginx Server

Nginx server settings can be modified inside the file nginx.conf. Open this file and check for the directive client_max_body_size. Then, change the value (in megabytes) to your maximum file size preference.

If you do not see this directive in nginx.conf, you can add it to the end of a server, location, or http block like so:

 
server {
          ...
          client_max_body_size 64M;
}

This allows for a 64-megabyte upload. Set this number to your preference, save the file, then reload Nginx for the change to take effect.

Apache Server

Change the size limit on an Apache server by updating your .htaccess file like so:

1. In your cPanel menu, select File Manager under Files.

2. In your root WordPress directory (public_html by default), locate .htaccess. Depending on your settings, the .htaccess file may be hidden.

3. Select .htaccess and click the Edit icon.

4. Copy and paste the code below at the bottom of your .htaccess file:

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

5. Click Save and reload Apache.

Doing this sets the maximum allowed size of your WordPress uploads and posts to 64 megabytes and sets the maximum file upload time to 300 seconds. You can change both of these values to your preference.

Still getting a 413?

After trying one or more of the solutions above, you still may encounter a 413 error when uploading large files, even if these files are below your new size limit.

In this case, the issue may stem from your CDN’s servers or some other restriction set by your hosting provider. First, reach out to your hosting support, detailing the problem and the steps you’ve taken so far to resolve it. It may be that you’ve exceeded your plan’s file size limit without realizing. Or, your configurations may have inadvertently caused another error.

If you use a CDN to improve your site’s performance, this may also be the cause of your issue — the CDN servers you’re using may impose file size limits that are too small. Since you probably can’t modify these servers’ files directly, you consult the documentation for your CDN provider or contact product support to resolve the error.

If all else fails, consider uploading alternative files, reducing the size of your current file, or upgrading your storage plan. If you find yourself needing to upload a massive amount of data, more likely than not there’s a workaround.

Fixing a 413 Error

While HTTP errors can be frustrating, many are quickly solvable including a 413. By finding and tackling this issue now, you’ll have one less thing to worry about while building out your website. If your site allows users to upload their own content, changing your upload size limit solves this problem too — just make sure you’re not exceeding the limits set by your hosting plan.

As for the best option, we recommend WordPress users modify their server’s PHP.ini file first if possible, since this can easily be done through your hosting panel. Otherwise, choose the option that matches your server software.

This post was originally published in January 2021 and has been updated for comprehensiveness.

New Call-to-action

Иногда при загрузке больших файлов на какой-либо веб-сайт может возникнуть ошибка, которую возвращает веб-сервер 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 а также информационной безопасностью.

Is your website showing a 413 request entity too large error? We are here to help you.

The 413 error simply means that the browser request was too large for the webserver to process.

Again, the fix for 413 request entity too large error involves modifying the size of the request body that the server accepts.

At Bobcares, we manage web servers for our customers as part of our Server Management Services.

Today, we’ll see how our Expert Engineers fix 413 errors in popular webservers like Apache, Nginx, and IIS.

Common scenarios of 413 request entity too large error

Let’s first have a quick look at the common scenarios that show the 413 error.

In general, most users experience the error while trying to upload files to the server.

For instance, in WordPress, it can happen during a theme or a plugin file upload using the WordPress dashboard. Or when a visitor tries to upload a large file, the error shows up as:

413_request_entity_too_large_error

Similarly, the same error can appear while trying to restore a large WordPress backup too.

In a recent Helpdesk request, the customer reported the error as:

The upload page on my website shows the request entity is too large error. A reload will always fix it. Any clue how to prevent that issue?

What exactly causes a 413 error?

Now that we know the various scenarios of the error, we’ll see the reason for the error.

The 413 request entity too large error happens when the browser requests a very large file that the webserver cannot process. In other words, it means that the client’s HTTP request is too large for the server to handle.

For security reasons, every web server limits the size of the client request. This helps to avoid any resource abuse on the server.

For example, when any visitor tries to request a big file, it can even slow down the entire server. In many attacks, overloading the server with huge sized requests is a common method. When the request body is larger than the server allowed limit, it ends up in the 413 error.

413_Request_entity_too_large

How we fix 413 request entity too large error

The fix for 413 request entity too large error is to increase the maximum request size that a web server can process. This again varies depending on the type of web server that the website uses.

Having a decade of experience in managing various servers, let’s see how our Dedicated Engineers fix this error in different web servers.

In IIS web server

To resolve the 413 error in IIS, we increase the value of the “uploadReadAheadSize” parameter. This value determines the number of bytes that IIS will read to run the respective IIS module.

The steps for modifying applicationHost.config on an IIS7 web server are:

  1. In IIS7, select the website.
  2. Then go to the “Configuration Editor“, in the drop-down menu, select “system.webServer
  3. Select “serverRuntime“.
  4. Find “uploadReadAheadSize” and increase its value.
  5. Finally, click Apply.

Solution for 413 request entity too large error in Apache

Similarly, when the website runs on an Apache webserver, we edit the value of LimitRequestBody in the configuration.

Based on the setting, we modify it in either the httpd.conf file or in a local .htaccess file inside the website.

To restrict the Apache requests beyond 50MB, we set the value as:

 LimitRequestBody 52428800

Then we do a config test, followed by a server reload.
service apache2 reload

Now the new value will be effective and the upload works fine.

Setting a value of 0 will allow any client request. But for security reasons, we never recommend it.

For Nginx webserver

Similarly, one of our customers came with a similar request on his Nginx server.

I have done a silly thing on my WordPress site and I need to reinstall my backup. However, I am getting an error message when I try to restore the site. The server responded with a “413 Request Entity Too Large”, please make sure that the server is not blocking our requests.

Here, we modified the value of the client_body_max_size directive in the Nginx configuration.

We opened the file at /usr/local/nginx/conf/nginx.conf and then modify the value as

# set client body size to 50M #
client_max_body_size 50M;

Then we restarted the Nginx server. This fixed the 413 Request Entity Too Large error.

Cross-checking PHP limits

In some cases, even if the webserver allows the client request size, often PHP limits on the website can throw up errors. Therefore, our Dedicated Engineers always cross verify the server limits for

  • upload_max_filesize
  • post_max_size
  • max_execution_time

And, we modify the values either using .htaccess file or php.ini file depending on the website settings.

[Looking for a fix for a 413 error on your website. We are here to help you.]

Conclusion

To sum up, the 413 Request Entity Too Large error occurs when the client browser request is too large for the webserver to handle. Today, we saw how our Support Engineers modify the value of HTTP request size limit in IIS, Apache, and Nginx.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

If you have come across this article it is likely that you are trying to configure your ASP.NET application (Core, MVC, Web API, Windows Forms, WCF or other) on an IIS web server which, unlike the development web server , refuses to accept the upload of a file larger than 16kb, returning one of the following errors:

HTTP Error 413.1 — Request Entity Too Large

(413) Request Entity Too Large

Maximum request length exceeded

All these errors are related to exceeding the maximum size of an attachment — or rather, the HTTP Request sent to the server — provided by our ASP.NET application by default. These limitations have been inserted for a valid reason: receiving a file is a rather heavy operation for the server, as it engages a working thread indefinitely. For this reason, the default settings of most ASP.NET applications provide a size generally between 16k and 64k, sufficient for sending / receiving text forms but logically completely inadequate when you need to manage the upload of one or more files.

Luckily enough, solving this problem is quite simple: all we have to do is modify some sections in the application’s Web.config file to extend the limits in bytes normally provided for this type of operation. Since these settings vary according to the versions of IIS, we have entered all the versions for which it is necessary to add (or change) the indicated values.

MaxRequestLength

This value sets the maximum length limit of each Request to a maximum of 1073741824 bytes.

IIS (all versions)

<configuration>

    <system.web>

        <httpRuntime maxRequestLength=«1048576» />

    </system.web>

</configuration>

IIS (version 7.x and higher)

In addition to the above:

<system.webServer>

   <security>

      <requestFiltering>

         <requestLimits maxAllowedContentLength=«1073741824» />

      </requestFiltering>

   </security>

</system.webServer>

HttpBindings

If your application is a web service built with ASP.NET WFC (SOAP) or Web API / MVC (REST), you also need to add the following attributes to the bindings you intend to use. The best way to proceed is to open the Web.config for the application and, under each of them, add the following highlighted parameters:

<system.serviceModel>

  <bindings>

    <basicHttpBinding>

      <binding

        maxBufferPoolSize=«2147483647»

        maxReceivedMessageSize=«2147483647»

        maxBufferSize=«2147483647»

        >

      <!— binding config: security, httpTransport and more  —>

      </binding>

    </basicHttpBinding>

  </bindings>  

</system.serviceModel>

The above example has the purpose of increasing the maximum size of any upload up to 2147483647 bytes for all basicHttpBinding connections: depending on the characteristics of your web service and the protocols used, it may be necessary to add the above attributes also to the other bindings present, expected and / or supported: webHttpBinding, wsHttpBinding, customBinding and so on.

In case such addition is not enough to solve the problem, it may be necessary to also change the transferMode attribute, setting it to Streamed (the default is Buffered), and also revise the settings related to the readerQuotas, i.e. the limitations that the server gives to the SOAP clients when initiating their connection:

<binding

      maxBufferPoolSize=«2147483647»

      maxReceivedMessageSize=«2147483647»

      maxBufferSize=«2147483647»

      transferMode=«Streamed»>

      <readerQuotas

          maxDepth=«2000000»

          maxStringContentLength=«2147483647»

          maxArrayLength=«2147483647»

          maxBytesPerRead=«2147483647»

          maxNameTableCharCount=«2147483647»/>

uploadReadAheadSize

In the event that all the operations described above are not sufficient to solve the problem, all that remains is to try to intervene by changing the value of the uploadReadAheadSize property: unfortunately, this setting cannot be changed at the Web.config level but must be defined directly on the machine hosting the publishing IIS Web Server.

The need to modify this setting is particularly frequent when working with the Windows Communication Foundation (WFC), the (not so much) «modern» method of managing SOAP Web Services that we have already had occasion to talk about in this article: in those scenarios, the problem generally occurs in consequence of any upload larger than 42-49kb.

Let’s get to work: access the server using Remote Desktop or physical access, then open a Command Prompt with administrator privileges and type the following command, taking care to replace YOUR_WEBSITE_NAME with the name of the website as you defined it on IIS Manager at the time of creation:

C:WindowsSystem32inetsrvappcmd  set config «YOUR_WEBSITE_NAME»

     section:system.webServer/serverRuntime /uploadReadAheadSize:«2147483647»

     /commit:apphost

In case you want to operate in a more general way, you can set this new value as a default setting for all websites with the following PowerShell command:

Set-WebConfigurationProperty -pspath ‘MACHINE/WEBROOT/APPHOST’ -filter «system.webserver/serverruntime» -name «uploadreadaheadsize» -value 1048576

If you prefer to use the GUI, you can also configure these settings via the  Configuration Editor within the Internet Information Services Manager (IISManager) tool:

HTTP Error 413.1 - Request Entity Too Large - How to fix

Once there, select the system.webServer/serverRuntime within the top-left dropdown list, the change the uploadReadAheadSize value to your new desired standard (2147483647 in our example):

HTTP Error 413.1 - Request Entity Too Large - How to fix

IMPORTANT: Make sure the enabled attribute is correctly set to True, otherwise the whole section will not be taken into account and IIS will use the default limitations, blocking uploads larger than 42-49kb.

That’s it for now: happy upload!

Sometimes, a website shows annoying errors confusing users while browsing. If browsing other sites makes you annoyed when it comes to your site, things are very different. Many types of website errors occur, some generic and others specific to WordPress. One such error is 413.

Error 413 belongs to the family of HTTP 4xx status codes, which identify errors connected to the request made by the client. In this article, you will see what the “413 Request Entity Too Large” error is and how you can fix it in your WordPress.

  • What Is the “Error 413 Request Entity Too Large” Error?
  • Why Does “413 Request Entity Too Large” Error Occur?
  • Fixing the “413 Request Entity Too Large” Error in WordPress

HTTP Error 413 indicates that the request made cannot be managed by the server, and this is because it involves a file or a block of data or, again, a group of files that are too large compared to the maximum limit that the server can manage.

The browser window generally displays the message “413 Request Entity Too Large”. This problem can occur if you try to upload too large files via the browser, exceeding the limits imposed by the webmaster for security reasons or others.

Why Does the “413 Request Entity Too Large” Error Occur?

Error 413 Request Entity Too Large occurs when you try to upload a file that exceeds the maximum upload limit set on your web server. In other words, when you try to upload a file that is too large, the web server returns an error message informing the user that “413 Request Entity Too Large”.

The message shown to the user may vary depending on the web server and the client. The following are the most common messages that indicate the occurrence of this error:

  • Error 413
  • HTTP Error 413
  • HTTP Code: 413
  • Request Entity Too Large
  • 413. That’s an error.

Fixing the “413 Request Entity Too Large” Error in WordPress

As you know, error 413 usually occurs when you upload a large file to your web server, and your hosting provider has set a limitation on file size.

One of the common problems webmasters encounter when managing WordPress is allowing the webserver to allow file uploads via the Media Library. However, if your Nginx-powered website is not configured to allow the uploading of large files, the upload process will mostly fail.

I will show you some of the easiest methods to increase the file upload size and fix the 413 Request Entity Too Large error in WordPress.

  1. Reset File Permissions
  2. Manually Upload the File via FTP
  3. Increase Upload File Size
  4. Modify Your Functions.php File
  5. Modify Your .htaccess File
  6. Modify Your nginx.conf File
  7. Contact Your Hosting Provider

1. Reset File Permissions

It might be possible that you are encountering this error due to limited access to a file and upload permission. So, it would be great to check the WordPress file/folder permissions and set the recommended permission, then try uploading the file to your site.

You can set the permissions from an FTP Client like FileZilla, and if your hosting provider offers any file permission reset option, then you can fix it from there.

reset file permission to fix 413

2. Manually Upload the File via FTP

It’s a good idea to consider FTP to upload your large file, but please note that if you are uploading a file via FileZilla, it takes more time.

Here, you will need to access your web server and upload the file by drag and drop. Therefore, first, you need to check whether your hosting provider offers server credentials or SFTP access to your web server.

server credentials

Now, you need the FileZilla FTP Client to access your web files, so download it if you don’t have one. Then, open FileZilla and fill the respective fields; Host, Username, Password, and Port. You can see in the below screenshot that I pasted my server IP, Username, Password, and 22 as a port number.

connect filezilla

Next, drag the file you want to upload to your website from your local desktop (left-side) and drop it into your web server’s folder. In my case, the webserver folder path is /applications/dbname/public_html/wp-content/uploads. If you want to upload any plugin then the folder path is /applications/dbname/public_html/wp-content/plugins.

3. Increase Upload File Size

Many good WordPress hosting providers offer the file size settings feature on their platform that lets users increase the maximum upload size value, maximum execution time, post max size, and more.

Now, let’s look at how you can increase your upload file size from the hosting dashboard. Cloudways offers application and server settings from which you can increase your file upload settings. From the Application Management panel, I have to remove comment “;” from three values and increase the upload and post max size to 256M & execution time to 300.

php_admin_value[post_max_size] = 256M

php_admin_value[upload_max_filesize] = 256M

php_admin_value[max_execution_time] = 300

setting file upload size from hosting panel

To check whether the file size value is updated or not, you need to create an info.php file on your desktop and upload it to your website folder via FileZilla. Now, open any file editor like Notebook, paste the following code, and save it as info.php.

<?php

phpinfo();

?>

info.php

Now, upload it to your site’s public_html folder.

upload info.php file

In the next step, open your browser and run this URL “www.yoursite.com/info.php”. In my case, the URL is https://wordpress-675386-2363839.cloudwaysapps.com/info.php. Search for the PHP admin values that you updated; if the values are changed, you have successfully increased the file size. After this, try to upload your file and check whether the issue has been resolved or not.

info.php on browser

If your hosting provider doesn’t offer any feature to modify the file upload size, move to the next method.

4. Modify Your Functions.php File

You can edit your theme’s functions.php file and increase the file upload size. But before that, you will need to create a backup of your entire WordPress site for data recovery. Backups help you recover your web files if something goes wrong.

You need an FTP Client like FileZilla to access your site’s file. So, connect your server via FileZilla and go to your active theme folder. You will find the theme files in the wp-content folder and in my case, the source path is “/applications/enxybqgzgy/public_html/wp-content/themes/twentynineteen”. Next, find the functions.php and click View/Edit.

edit functions.php file

Next, paste the following lines of code into your file and save it. This will define the max upload size in Megabytes. Replace the numbers as per your requirement.

@ini_set( 'upload_max_size' , '256M' );

@ini_set( 'post_max_size', '256M');

@ini_set( 'max_execution_time', '300' );

After this, check open info.php on your browser “www.yoursite.com/info.php” and check whether the values are updated or not, then try uploading your file.

In case this doesn’t work, then move to the next method.

5. Modify Your .htaccess File

If your website is hosted on LAMP Stack (using Apache web server and PHP), you can increase the max upload size from your .htaccess file.

Again, you need to access your .htaccess file from an FTP client like FileZilla and go to the public_html folder. Search for the .htaccess file, and if you do not see the .htaccess file, it’s probably hidden. Hence, navigate to FileZilla menus > Server and click Force Showing Hidden Files.

view hidden files

Now View/Edit the .htaccess file in a code editor or Notepad and add the following lines.

php_value post_max_size 256M

php_value memory_limit 256M

php_value max_execution_time 300

Choose a number and size that is suitable for your site and file. Next, open info.php ““www.yoursite.com/infor.php”” on your browser to check the updated sizes as we did in the previous step.

6. Modify Your nginx.conf File

The above troubleshooting method is for Apache web server, but if you are running your website on LEMP (NGINX as a web server and PHP), you need to edit nginx.conf i.e., located in /etc/nginx/ and add the following line of code to the file.

http {

client_max_body_size 100M;

}

7. Contact Your Hosting Provider

If you tried all the above and are still facing the issues, then it would be good to contact your hosting support and ask them to fix this issue ASAP. Several hosting providers offer 24/7 support chat and ticket assistance to help their customers.

Summary

Error 413 Request Entity Too Large is related to the size of the client request. There are multiple ways to fix this error you have read in this article. The most common way is to reduce the file size or to change the web server settings to increase the upload file size. If you know any other methods that can help fix the HTTP 413 Error, then please comment in the section below.

Frequently Asked Questions

Q. How do I fix Error 413 Request Entity Too Large?

A. The most common way to fix the HTTP 413 Error is to increase the media file maximum upload size. Other ways are: resetting file permissions, uploading files using an FTP client, and modifying your files (fuctions.php/.htaccess/nginx.config).

Q. What does “HTTP Error 413” mean?

A. If a user gets this error it is because he’s uploading a file that is too large. When a webmaster receives this report, what he can do is ask the user to reduce the file size and try to upload it again.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Access error 3128
  • Access error 3048
  • Access error 2950
  • Access denied try again later как исправить
  • Access denied steam как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии