Сообщение об ошибке сервера 500 на стороне клиента или в панели администрирования может стать источником серьезных проблем и причиной потери посетителей. Устранить внутреннюю ошибку сервера HTTP 500 особенно сложно, потому что причины возникновения подобной неполадки могут быть самыми разными.
Формат сообщения о внутренней ошибке сервера 500 не предполагает никаких пояснений о возможном источнике проблемы, и на поиск причины возникновения неполадки могут уйти часы терпеливой работы. В это время сайт теряет посетителей и возможные продажи, страдает репутация компании.
Если на вашем сайте появилось сообщение о внутренней ошибке сервера HTTP 500, понадобятся все возможные способы устранения возникшей проблемы, которые рассмотрены в этой статье. Надеюсь, это руководство поможет вернуть сайт в рабочее состояние в кратчайшие сроки.
- Краткая справка: внутренняя ошибка сервера 500 в WordPress
- Создайте резервную копию сайта
- Перезагрузите страницу
- Проверьте журнал сервера
- Очистите кэш браузера
- Проверьте доступность панели администратора
- Отключите тему оформления или плагин, вызывающие ошибку
- Проверьте файл .htaccess
- Увеличьте лимит памяти для PHP
- Проверьте права доступа
- Переустановите WordPress
- Обратитесь в техподдержку
- Обратитесь к специалисту по отладке
- Заключение
Подобное сообщение уведомляет пользователей о том, что неполадка в работе WordPress-сайта возникла на стороне сервера. В браузерах посетителей сайт не отображается. Эта ошибка особенно опасна тем, что может помешать входу в панель администрирования.
Вопреки распространенному мнению, подобная ошибка не связана с неполадками в работе сервера. Она указывает на проблему с корневым каталогом WordPress-сайта. Это означает, что для обнаружения истинной причины возникшей проблемы понадобится немало проб и ошибок. В зависимости от используемого браузера, сообщение об ошибке выглядит по-разному:
- 500 internal server error (500 внутренняя ошибка сервера);
- Internal server error (внутренняя ошибка сервера);
- Error 500 (ошибка 500);
- HTTP error 500 (HTTP ошибка 500);
- HTTP error 500-internal server error (HTTP ошибка 500 – внутренняя ошибка сервера);
- Temporary error (500) (временная ошибка 500);
- Error code: 500 (код ошибки: 500).
Независимо от формата сообщения, ошибка 500 возникшая на WordPress, негативно повлияет на индексирование в поисковиках, репутацию, трафик, и, конечно же – продажи. Ниже приведена инструкция с перечнем наиболее эффективных методов решения проблемы.
До начала каких-либо действий по поиску причин возникновения ошибки 500 следует провести резервное копирование сайта, если бекапа у вас нет или он уже устарел. Процесс решения подобной проблемы может вызвать серьезные изменения в корневом каталоге, где хранятся все файлы WordPress. При наличии резервной копии сайта можно не опасаться любых изменений. Используйте плагин для автоматического создания резервной копии, затем сохраните бекап на внешнем носителе или в облачном хранилище.
Это самое первое, что стоит сделать – возможно, серверу просто понадобилось очистить кэш или удалить временные файлы. Внутренние ошибки сервера часто возникают после обновления сайта, активации новой темы, добавления плагинов. Сервер может быть перегружен, и сообщение об ошибке просто исчезнет после перезагрузки сайта. Если такое случается часто – это повод подыскать более надежный хостинг для WordPress.
Также стоит проверить работоспособность сайта с помощью сервиса downforeveryoneorjustforme.com – он покажет, если интернет-ресурс полностью недоступен всем посетителям, либо проблема находится на вашей стороне.
Содержимое лога сервера может пролить свет на причины возникновения проблемы. Журналы сервера предоставляют ценную информацию, и помогут выяснить многие причины возникновения неполадки. Среди возможных причин может оказаться установка некорректной темы оформления, плагина; ошибки при установлении соединения с базой данных.
При ошибках, связанных с базами данных, браузер обычно показывает пустую страницу, которую иногда называют «белым экраном смерти». Вследствие отсутствия соединения с базой на экране не будет никаких данных. Эта неполадка не только уничтожает клиентскую часть сайта, но и лишает администратора доступа в панель управления.
Основные причины подобной проблемы следующие:
- Поврежденный файл базы данных WordPress.
- Повреждение файлов движка WordPress злоумышленниками или вирусами.
- Перегрузка базы данных запросами при большом объеме трафика – такое чаще всего происходит на общих хостингах.
Для решения возникшей проблемы, прежде всего, проверьте корректность параметров конфигурации базы данных, или восстановите базу данных из резервной копии. WordPress также предоставляет встроенный метод исправления нерабочей базы данных следующей командой:
Define(‘WP_ALLOW_REPAIR’, true);
Очистка кэша улучшает производительность браузера и решает многие проблемы с неправильной загрузкой сайтов. Существует множество эффективных и бесплатных утилит для полной очистки кэша.
Попробуйте зайти в панель управления по стандартной ссылке. Если попытка не удалась, сообщение о внутренней ошибке сервера 500 может указывать на проблему с недавно установленными темами оформления и плагинами.
Если вам не удается войти в панель администрирования WordPress для отключения некорректной темы оформления или плагина, придется действовать обходным путем. Способ прост, хотя и займет некоторое время. Понадобится FTP-клиент для прямого доступа к файлам сайт. Скачайте, например, FileZilla, введите в параметрах соединения адрес сайта, логин и пароль, подключитесь к серверу – файлы вашего сайта будут в окне справа.
Найдите папку под названием plugins и переименуйте ее в plugins_deactivate. Все плагины будут отключены. Перезагрузите сайт – если ошибка исчезла, значит, причина была в плагине. Теперь вы можете войти в панель администрирования. Войдите и начните активировать плагины по одному. Перезагружайте сайт после активации каждого плагина – так вы обнаружите проблемный. Удалите его, найдите ему замену или уведомите разработчика о проблеме, с которой вы столкнулись. Не забудьте вернуться в FTP-клиент и переименовать директорию обратно, чтобы исправные плагины стали активными.
Если окажется, что ошибку вызывают не плагины, проделайте эти же самые шаги, последовательно проверяя все темы оформления в папке themes. Удалите проблемную тему оформления и перезагрузите сайт.
Установка новой темы оформления или плагина могут вызвать изменения в файле .htaccess, что также может стать причиной сообщения о внутренней ошибке сервера. Эту проблему легко решить с помощью FTP-клиента.
Найдите файл .htaccess, кликните по нему правой кнопкой мыши и переименуйте в .htaccess_old. Перезагрузите файл – если сообщение об ошибке исчезло, значит, проблема действительно была связана с файлом .htaccess. Войдите в панель администрирования, выберите раздел «Постоянные ссылки» в меню «Настройки», затем нажмите кнопку «Сохранить изменения». Эта процедура восстановит оригинальный файл .htaccess и избавит вас от ошибки 500.
Если ваш WordPress-сайт использует множество скриптов, перегружающих доступный объем памяти, это также может стать причиной возникновения ошибки 500. Объем памяти регулируется настройками хостинга и движком WordPress. Увеличить объем памяти для PHP можно несколькими способами.
- Изменить параметры в файле wp-config.php. Зайдите в папку сайта с помощью FTP-клиента, найдите файл wp-config.php, кликните по нему правой кнопкой мыши и выберите в контекстном меню пункт «Просмотр/Редактирование». В качестве редактора по умолчанию можно использовать «Блокнот». Перед строкой «Happy Blogging» добавьте следующий фрагмент кода:
define(‘WP_MEMORY_LIMIT’,’64’);
Сохраните отредактированный в «Блокноте» файл на своем жестком диске, найдите его в левом окне FTP-клиента, кликните по нему правой кнопкой мыши и выберите в контекстном меню пункт «Загрузить». Если после перезагрузки сайта ошибка 500 исчезла – проблема была в доступном объеме памяти.
- Отредактировать файл php.ini. Чтобы найти этот файл, активируйте опцию «Показывать скрытые файлы»; файл php.ini расположен в подкаталоге wp-admin корневой директории. Откройте файл php.ini, найдите строку, начинающуюся с «memory_limit». Если указанное значение составляет 64 Мб и менее, замените его новым параметром:
Если вам не удалось найти файл php.ini, создайте его самостоятельно с помощью программы «Блокнот». Вставьте в созданный файл приведенный выше код и загрузите его на хостинг, в папку wp-admin.
- Изменить файл .htaccess. С помощью FTP-клиента найдите файл на хостинге и добавьте в него следующую строку:
php_value memory_limit 256M
Это увеличит лимит памяти до 256 Мб. Если вы не смогли найти файл .htaccess – активируйте опцию «Показывать скрытые файлы» или создайте подобный файл самостоятельно, после чего загрузите его в папку wp-admin.
Чтобы избежать повторного появления ошибки 500, придется выяснить, какой именно компонент сайта перегружает память. Это может быть некорректно написанный плагин или тема оформления. Можно обратиться за помощью в техподдержку хостинга – специалисты смогут выявить проблемный компонент с помощью журнала сервера.
В соответствии с правилами безопасности WordPress, протокол назначения прав доступа выглядит следующим образом:
- Все директории должны иметь права 755 или 750.
- Для файлов назначают права 644 или 640, кроме файла wp-config.php, который должен иметь права 400 или 440 с целью обеспечения защиты от несанкционированного доступа.
- Ни в коем случае не назначайте права 777 для директорий.
Если права доступа имеют какие-либо другие параметры, возможно появление ошибки 500. Параметры можно проверить с помощью FTP-клиента – они указаны в «Разрешениях». Если вы обнаружите файл или папку с правами доступа, отличающимися от регламентированных – кликните правой кнопкой и измените соответствующий параметр на правильный.
Системные файлы могут повреждаться со временем, в таком случае понадобится переустановка WordPress. Такие повреждения случаются редко, но если все рассмотренные выше методы не помогли, это единственный оставшийся вариант. Переустановка ничем не отличается от первоначальной установки WordPress – скачайте свежий установочный файл с www.wordpress.org и установите WordPress на свой хостинг.
Установочные файлы находятся в папке WordPress. Подключитесь к серверу с помощью FTP-клиента, найдите папки wp-admin и wp-includes, начните загрузку файлов. Когда появится запрос о действиях с существующими файлами, выберите «Переписать». Эта операция заменит все старые файлы в директориях wp-admin и wp-includes новыми. Если после перезагрузки сайта все заработает правильно – проблема была в поврежденных файлах WordPress.
Если все приведенные выше способы не решили проблему, обратитесь в техподдержку хостинга. При выборе надежного хостинга для WordPress всегда важно учитывать наличие в штате специалистов, имеющих опыт в решении проблем с внутренней ошибкой сервера 500. Специалисты исправят подобную ошибку самостоятельно или проведут владельца сайта шаг за шагом через все этапы, необходимые для решения проблемы.
WordPress включает в себя инструмент для тестирования и отладки. Он пригодится, если источник возникшей проблемы остается неясным. В ходе отладки в файл wp-config.php вставляют фрагменты кода, который поможет определить причины неполадок. Результаты тестов записываются в файл, расположенный в корневом каталоге. Для интерпретации и последующей настройки лучше обратиться к опытному профессионалу: новичку сложно отличить незначительную ошибку от серьезной. Кроме того, в процессе тестирования фрагменты кода могут быть видны посетителям сайта.
Внутренняя ошибка сервера 500 досадна – особенно потому, что причины ее появления часто неясны, а единственного простого решения не существует. Приведенные в этой статье методы не требуют навыков программирования, но в большинстве случаев помогут решить возникшую проблему.
Если сайт расположен на бюджетном общем хостинге, лучше сменить тарифный план или выбрать хостинг-провайдера, который возьмет на себя обязательства по обеспечению стабильной работы вашего интернет-ресурса.
Большинству из нас, будь то разработчики, дизайнеры или даже конечные пользователи, приходилось хотя бы раз в жизни пережить. То есть болезненный процесс получения внутренней ошибки сервера и попытки ее исправить. Многие люди не хотят знать больше – они просто хотят это исправить. Но если вы не попытаетесь хотя бы понять это, вам придется чаще страдать от этой участи. Ошибка внутреннего сервера 500 очень важна, поскольку она полностью останавливает все процессы и может вывести из строя весь ваш сайт. Так что, если мы когда-нибудь захотим от него избавиться, нам нужно сначала лучше понять, что это значит.
В этой статье я расскажу, что означает эта ошибка, как определить проблему и, конечно же, как ее исправить. Но прежде чем начать, я хочу провести вас через различные существующие ошибки http (сайта) и то, что они потенциально могут означать. Если хотите, можете сразу перейти к тому, как исправить ошибку WordPress 500.
Общие коды состояния и ошибок HTTP
Перво-наперво – я собираюсь объяснить, что на самом деле означают эти ошибки. В настоящее время существует список состояний и ошибок для HTTP, к которым можно получить доступ, чтобы лучше устранить проблему. Эти ошибки обычно делят по типам. Итак, чтобы сократить этот вопрос, мы рассмотрим наиболее важные ошибки и информационные коды состояния, которые вы найдете при работе со своим сайтом WordPress.
100x ответ (статус)
Этот тип ответа предоставляется непосредственно веб-сервером. В зависимости от вашей хостинговой компании ответ может быть предоставлен Apache, nginx или любым другим веб-сервером, который использует компания. Этот тип ответа не связан с ошибками. Обычно они используются, чтобы указать, что соединение установлено. Это коды состояния ответа на соединения.
200x ответ (успех)
Я называю их успешными. Такой ответ всегда свидетельствует об успехе. Это означает, что либо сервер успешно подключился к вам, что запрашиваемые ресурсы были предоставлены правильно, либо было установлено прокси-соединение.
Самый распространенный успешный код известен как 200 OK. Вы можете увидеть примеры этого, если используете инструмент тестирования скорости WordPress, скажем, в Pingdom Tools, и пытаетесь узнать FTTB (первый раз в байтах). Ответ 200 OK всегда выдается на первый сделанный запрос.
300x ответ (перенаправления)
Ребята перенаправления. Эти коды всегда передаются, если данная ссылка переадресовывается. 300 кодов состояния указывают на успешное перенаправление и также не считаются ошибкой.
Предположим, у вас есть сайт SSL (HTTPS), и у вас также есть прямой доступ к HTTP (незащищенный), и вы хотите перенаправить всех на HTTPS-версию своего сайта. Вы можете создать перенаправление для всех запросов, поступающих с HTTP, на HTTPS. Если вы случайно попытаетесь зайти на свой сайт по HTTP, ваш браузер получит ответ 300, указывающий на перенаправление на версию HTTPS.
Другой распространенный пример, с которым вы, возможно, знакомы, – это локальные перенаправления для SEO. Возможно, вы удалили старые сообщения или страницы. С помощью такого плагина, как Yoast SEO, вы можете 301 перенаправить их на новые, более релевантные страницы. Или используйте временное перенаправление 307, если вы работаете над обновлением и хотите ненадолго перенаправить пользователей на другую страницу.
Ответ 400x (ошибки клиента)
Известные клиентские ошибки. Эти типы ошибок связаны с проблемами в вашем браузере. Как правило, не удается загрузить определенный актив (наиболее известной является ошибка 404). Это коды ошибок, которые не считаются серьезными.
Та же ошибка может появиться, если вы попытаетесь получить доступ к несуществующему изображению на вашем сайте. Например, вы можете использовать перенаправление 410, чтобы сообщить поисковым системам, что контент был окончательно удален, или 451, если вы сделали страницу недоступной по юридическим причинам (например, по запросу DMCA).
Ответ 500x (ошибки сервера)
И вот мы подошли к нашему главному герою. 500 ошибок. Как видите, это важные ошибки, которые всегда связаны с самим сервером. Ошибки сервера важны, потому что они могут привести к сбою вашего сайта. Из этих ошибок наиболее важными являются:
- Услуга A 503 недоступна
- Ошибка 502 неверного шлюза
- Внутренняя ошибка сервера 500
Давайте рассмотрим 3 из них в порядке важности.
сервис 503 недоступен
Наименее серьезным является недоступность службы 503. Если эта ошибка появляется, у вас проблема с ресурсами на веб-сервере. Почти всегда это появляется, когда ваш сервер перегружен. Проще говоря, если вы видите эту ошибку, знайте, что она временная и напрямую связана со слишком большим объемом трафика, и это приводит к перегрузке процессора. Когда ЦП и сам веб-сервер не могут обрабатывать больше входящих подключений, потому что он достиг 100% загрузки ЦП, вы увидите это всплывающее окно с ошибкой.
Вы можете исправить это, либо переключившись на лучший веб-сервер (например, с Apache на Nginx), либо внедрив плагин кэширования WordPress на свой сайт.
502 Неверный шлюз
Это то, что я назвал ошибкой неправильной конфигурации. Эта ошибка не появляется без причины. Если у вас когда-либо возникала эта ошибка, скорее всего, причина в том, что вы что-то сделали, но сделали это неправильно. Обычно это происходит, когда люди пытаются настроить Apache и конфигурацию PHP или при попытке оптимизировать nginx. Плохой шлюз – это ошибка, которая почти всегда возникает, когда PHP FPM (Fast Process Manager) теряет соединение. Либо из-за неправильной настройки, либо из-за сбоя процесса. Это приводит к тому, что веб-сервер отвечает неверным шлюзом.
Самый простой способ исправить эту ошибку – дважды проверить конфигурацию PHP-FPM, поскольку это наиболее вероятная причина этой ошибки. Это происходит чаще на стороне Nginx, чем на Apache, и почти никогда не происходит на службах хостинга, предоставляемых cPanel или Plesk. На последних двух панелях предусмотрены меры предосторожности для предотвращения ошибки неправильной конфигурации. Но это происходит очень часто при управлении собственным VPS.
Нужна дополнительная помощь с этим? Следуйте нашему руководству о том, как исправить ошибку 502 неверного шлюза.
500 – внутренняя ошибка сервера
Большой плохой мальчик ошибок. Внутренняя ошибка сервера 500 – худшая из них, прежде всего потому, что это такая общая ошибка. Если у вас нет достаточных знаний о том, как с этим бороться, это может стать настоящей болью, поскольку может вывести из строя весь ваш сайт. Ошибка 502 неверного шлюза также вызывает сбой вашего сайта, но ее легче диагностировать и исправить. Как уже упоминалось, это почти всегда связано с конфигурацией FPM.
Причины 500 внутренних ошибок сервера и способы их устранения
Первое, что нужно понять об ошибке 500, – это то, что она может быть вызвана рядом различных факторов, которые почти всегда связаны с сбоями в выполнении кода. Вместо того, чтобы пытаться диагностировать все сразу, я дам вам список ошибок по типу проблемы и тому, что вы делали.
- Путем переноса старого сайта на новый хостинг
- Ошибка в .htaccess в конфигурации apache
- Ошибка выполнения PHP-кода
Существуют и другие, менее распространенные случаи, которые могут вызвать внутреннюю ошибку сервера 500, но для простоты и удобства использования этой статьи я сосредоточусь на этих трех.
1 Перенос старого сайта на новый хостинг
Эта ошибка может появиться несколькими способами, но почти всегда кажется, что это связано с версией PHP, привязанной к вашему веб-серверу. Более новые версии PHP могут немедленно вызвать внутреннюю ошибку сервера 500, если текущий сайт или плагины не поддерживают текущую версию.
Эта ошибка является классической, например, когда вы переносите свой сайт с посредственного хостинга со старой версией PHP на более новый хостинг, который принимает только более новые версии (7.0 и выше). Если ваш сайт не обновлялся в последнее время, возможно, проблема связана со старым плагином. Я называю это «внутренней ошибкой сервера миграции», потому что это почти всегда происходит при миграции сайта.
Решение
Лучший способ исправить эту ужасную ошибку, когда вы так сильно пытаетесь перенести свой сайт WordPress на новый хостинг, – это сделать полную копию ваших плагинов и темы вашего сайта. После этого удалите все плагины со своего сайта и попробуйте еще раз. Если ошибка исчезнет, почти гарантировано, что ошибка была сгенерирована более новой версией PHP на вашем хостинге, которая просто отказывается выполнять код в вашем более старом плагине. Повторно загружая один плагин за раз, вы можете легко узнать, какой из них вызвал проблему.
Эти ошибки почти всегда проявляются при переносе старых сайтов, работающих на PHP 5.4 и 5.6, на новый хостинг с PHP 7.0, 7.1 или 7.2.
То же самое относится и к вашей теме. Поскольку темы могут реализовывать и реализуют дополнительный PHP-код в файлах functions.php, single и page.php. Скорее всего, более старая тема без обновлений может сломать ваш сайт после переноса на хостинг с более новой версией PHP. Эта ситуация прискорбна, поскольку единственный способ исправить это – изменить тему и перестроить ваш сайт. Это наихудший сценарий.
2 Ошибка конфигурации .htaccess Apache
Допустим, вы настраивали плагин, и вдруг все вылетает. Если вы получаете внутреннюю ошибку сервера 500 при настройке, например, плагина кэширования или любого плагина, связанного с оптимизацией, вам необходимо проверить, добавил ли плагин дополнительный код в ваш файл .htaccess.
Поскольку apache можно изменять в реальном времени, настраивая функции в файле .htaccess (который почти всегда скрыт), неправильная конфигурация может нарушить работу вашего сайта.
Решение
Чтобы исправить это, либо войдите в свой сайт через FTP и измените файл .htaccess, либо путем прямого редактирования, например, с помощью проводника файлов на cPanel или Plesk.
Если вы не знаете, как отменить то, что сделал плагин, и вам снова нужен ваш сайт, сделайте копию существующего содержимого в виде текстового файла. Сохраните это как резервную копию. Затем замените весь .htaccess следующим кодом:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule. /index.php [L]
</IfModule>
# END WordPress
Это файл .htaccess WordPress по умолчанию. Он должен работать с любым сайтом. Итак, если вы в отчаянии и не знаете, какую часть удалить, просто удалите все и вставьте этот код. Он мгновенно вас спасет. Позже вы можете удалить плагин или попробовать настроить его снова. Теперь вы знаете, как спасти вас от этой катастрофической ошибки. По крайней мере, если это связано с .htaccess.
Если вы не знаете, связана ли это с .htaccess, или эта ошибка начала появляться, даже если вы не касались каких-либо плагинов, не рискуйте. Просто скопируйте содержимое вашего .htaccess и скопируйте приведенный выше код, чтобы попытаться диагностировать. Если это не помогло, оставьте .htaccess как есть, а затем попробуйте следующее предложение.
3 Ошибка выполнения кода PHP.
Ошибки такого типа встречаются чаще, чем вы думаете, и обычно они возникают, если плагин выполняет недопустимый код. Самый распространенный способ выполнения недопустимого кода – это попытка выполнить устаревшие инструкции. Возможно, вы пытаетесь запустить старый плагин, который был разработан для работы только с PHP 5.4 или 5.6 с PHP 7.0 или более новыми версиями. Устаревшие и недопустимые функции вызовут внутреннюю ошибку сервера, которую можно диагностировать только путем включения режима отладки WP.
Включить wp_debug
Режим отладки WordPress предоставит вам подробную информацию об ошибке, которая остановила выполнение. Мы включаем его, изменяя значение с «false» на «true» в wp_debug внутри файла wp-config.php в корневой папке вашего сайта.
Если вы используете Plesk или cPanel, вы можете сделать это, просто изменив это значение с помощью проводника и отредактировав wp-config.php. Вы также можете следовать этому руководству по отладке от Blogvault, чтобы получить более подробные инструкции.
Как только файл будет отредактирован, вы сможете увидеть фактическую ошибку, которая остановила выполнение. В ошибке также будет указан путь и файл, в котором это произошло, поэтому легко догадаться, какой плагин вызвал ее. При отключении его можно пропустить ошибку, а затем обновить плагин или удалить его, в зависимости от ситуации.
Решение
Подавляющее большинство случаев внутренней ошибки сервера 500 связано с более старыми версиями тем или плагинами. Переключив вашу тему на любую стандартную тему WP, вы сможете восстановить доступ к своему сайту. Отключение конфликтующих плагинов также вернет вам доступ к панели управления. Если вы столкнулись с ситуацией, когда ваша тема является ответственной за нарушение работы сайта, лучший способ исправить это – создать zip-файл указанной темы из папки темы wp-content / themes / yourtheme, а затем удалить его из твой сайт. Это устранит ошибку, и вы сможете восстановить доступ к своему сайту. Затем вы можете повторно загрузить его и обновить, не активируя. То же самое можно сделать и с плагинами.
Наиболее частые ситуации для 500 внутренних ошибок сервера можно исправить обновлением. В случаях, когда для указанного плагина / темы нет доступных обновлений, вы можете попробовать переключиться на более старую версию PHP. Но знайте, что это временное решение. Новые версии PHP становятся стабильными, а старые версии регулярно объявляются устаревшими. Рано или поздно ваш сайт точно перестанет работать. Лучшим подходом всегда будет обновить или удалить / заменить соответствующие плагины.
Всегда помните, что лучше предотвратить и обновить, чем пытаться устранить повреждения позже.
Завершение нашего руководства по внутренним ошибкам сервера WordPress 500
Внутренняя ошибка сервера WordPress 500 может стать настоящей проблемой. Но в большинстве случаев их можно легко диагностировать и исправить, просто удалив / обновив конфликтующие части вашего сайта. Хотя могут быть ситуации, когда эти ошибки выходят за рамки нормы (например, при разработке плагина), это выходит за рамки цели данной статьи.
Для подавляющего большинства людей приведенный выше совет должен решить вашу проблему. Помните, что wp-debug – ваш лучший друг, и всегда внимательно следуйте инструкциям. Ваш сайт будет снова в сети в кратчайшие сроки.
Остались вопросы? Или советы по устранению внутренней ошибки сервера WordPress 500? Дай мне знать!
Источник записи: https://www.wpexplorer.com
Have you encountered an HTTP 500 Internal Server Error on your website? For most webmasters, this can be a frustrating situation.
If you don’t manage to catch the problem early enough, your site’s search engine visibility might take a hit. You might also lose some customers and sustain long-lasting reputational damage.
If spotted and corrected early enough, there may be little to no harm done. The real problem with 500 Internal Server Error is that you often have no clue what the root cause is.
The good news is that It is generally not a serious problem and 500 internal server errors can be easily fixed once you uncover the root cause.
If you follow all the steps we’ll show you in this guide, you will have your website back up and running in no time!
Table Of Contents
- What Does 500 Internal Server Error Mean?
- How to Resolve a 500 Internal Server Error (Without Coding)
- How to Backup Your Website
- How to Fix the 500 Internal Server Error in WordPress Step by Step (Advanced Troubleshooting)
- How to Prevent a 500 Internal Server Error
- Final Thoughts
What Does 500 Internal Server Error Mean?
The 500 Internal Server Error means that the server has been unable to fulfill the request due to an unexpected condition.
As a result, the page will not load and you will see a browser page outlining the error.
Chances are, if it’s down for you, it could be down for your visitors too, making this a vital error to tackle!
When you navigate to a website, you are accessing web files and content that are stored on a remote server. Your browser communicates with this server, requesting the content that you need.
In response, the server sends a HTTP response status code back to your browser, informing it of the status of the request. If successful, the code returned to the browser will be a HTTP code: 200 OK.
The server will then execute the commands, providing a copy of the relevant content to your browser.
If unsuccessful, the server might return one of two classes of codes: a HTTP 400 or 500. Broadly speaking, these aren’t single types of errors, rather, they are classes of errors.
For example, the range of HTTP 500 errors includes codes such as:
- 501 Not Implemented
- 502 Bad Gateway
- 503 Service Unavailable
Each of which indicates a different challenge to address.
How to Resolve a 500 Internal Server Error (Without Coding)
Before you get started with more technical troubleshooting, try these two basic fixes:
- Reload the page to resolve a 500 internal server error
- Clear the cache to troubleshoot a 500 server error
While a 500 Internal Server error can be annoying, it is typically easy to fix.
These errors can sometimes be caused by temporary, minor situations such as issues with your device, network, router or hosting service.
1. Reload the Page to fix HTTP Error 500
500 Internal Server errors can often be resolved with no need for complex troubleshooting.
Sometimes the problem is a temporary situation with your hosting service, ISP or local network. Simply refreshing the web page could be enough to load the site correctly.
If that doesn’t work, perhaps try a forced refresh. This ‘forces’ the browser to request a new page from the server rather than showing you its cached version. This is the best way to assess the current situation with any website.
You can use keyboard shortcuts to force-refresh your web pages. The combinations are slightly different depending on the browser and device you are working in.
Here are the combinations to try.
In Chrome, Firefox, or Edge on a Windows powered device, hold down Ctrl+F5 or Shift+F5 or Ctrl+Shift+R.
If you’re using Chrome or Firefox on a Mac device hold down Shift+Command+R.
2. Clear the Cache to Resolve an HTTP 500 Internal Server Error
Clearing the browser cache is a fundamental part of website troubleshooting. Browser caches help to speed up the browsing experience by storing bits of data from websites you have visited in the past.
Sometimes that cached data can become corrupted and communication between the browser and the website you’re looking at is interrupted. One symptom of this is the 500 error.
Clearing the cache is a straightforward procedure. The steps might differ slightly depending on the browser in use.
Here are the steps to clear your cache in Firefox, Safari, Chrome and Edge:
Firefox
Open up Firefox and click on the menu button.
Select Settings, then on the left hand side panel, select Privacy and Security > Cookies and Site Data and click clear data.
A popup will appear offering the option to check/uncheck Cookies and Site Data, and Cached Web Content.
What you’re after is cached content so tick this box and leave the Cookies and Site Data box unchecked. Click on Clear Data and the cache will be cleared automatically.
Safari
The process is even simpler in Safari.
To clear the cache in Safari click on the Safari menu > Empty Cache > Empty.
Chrome
To clear the cache in Chrome, open the browser and click on the three-dots icon in the topmost right hand corner.
On the dropdown menu, click on more Tools > Clear browsing data.
This will open up a new page where you will be presented with the options of clearing Browsing History, Cookies and Other Site Data, and Cached Images and Files.
Check the box to clear Cached images and files, click on Clear data, and that’s it.
Edge
Open the browser and click on the three-dot menu at the top right hand corner. Navigate to Settings > Privacy & Services.
You will see options for clearing different classes of browsing data. Choose Cached images and files and select Clear now.
Note that the precise steps may vary based on the version of the browser you are using.
If neither of these two simple fixes work, then you’re going to have to apply some more technical troubleshooting methods. Some of these may require making changes to your website or your web server.
Now would be a good time to make a backup.
Troubleshooting can be a risky process and people have been known to completely lose their data.
To avoid this, back up your data safely before you get started. Most hosting providers will keep a backup of your files, but you may not want to rely solely on this.
Read on for a complete step by step-by-step guide on how to back up your WordPress website.
How to Backup Your Website
There are several methods to back up a website. You can do this by installing a plugin, by downloading the files through FTP, or by creating a backup in cPanel.
Each method has its pros and cons and may be more or less suitable depending on your skill level.
Using a Plugin
There are a few plugins you can use to create a backup of your WordPress website. One that we recommend is Updraft.
Log in into the WordPress backend using the wp-admin path. Navigate to Plugins > Add new and search for Updraft.
Install and activate the plugin.
Once activated, a popup will appear, prompting you to ‘Press here to start’. You can also click on Settings under Updraft.
There are quite a few options under Settings which allow you to determine things like backup frequency, which files to include in a backup, how to save your backup, and so on. Set them up as you need.
Once you have made your choices, it’s time to put the plugin to work!
Still on the Updraft Settings page, click on the Backup/restore tab and then on Backup Now.
That’s it! Your website will be backed up.
For more detailed guidance, checkout our step-by-step guide on how to back up your WordPress website.
Backing Up Manually Using FTP/SFTP
File Transfer Protocol (FTP), is the traditional way of uploading and downloading data or content to or from your website. Secure File Transfer Protocol (SFTP) does the same thing but using extra layers of security.
To use this method, you will begin by connecting to your FTP server through an FTP client. The most popular one is Filezilla.
FTP allows for a transfer of files between two computers over a network. In this case, you will be uploading your data from your web server to your computer.
Begin by downloading the Filezilla Client and installing it on your desktop.
Next, you will need to have the FTP server address, along with your username and password. These details are usually provided by your hosting service.
You will then need to set the port to port 21 if you are using FTP, and port 22 if you are using SFTP.
Once your FTP client is all set up, the files and folders that make up your WordPress website will be visible for download.
All you will then have to do is drag and drop them into folders on your computer.
Use cPanel/Ask your Host
Most hosts provide default backup tools in cPanel. If you know your way around cPanel, this is a good option.
Login into cPanel and navigate to Files > Backup Wizard > cPanel Backup > Backup > Full Backup > Download a Full Account Backup > Generate Backup.
How to Fix the 500 Internal Server Error in WordPress Step by Step (Advanced Troubleshooting)
Once you have created a backup of your files, it will be time to turn to serious WordPress troubleshooting.
Here are the steps to follow, along with different methods for troubleshooting an internal 500 error on your WordPress website.
- Turn On Debugging
- Switch Themes
- Deactivate All Plugins
- Check the .htaccess File
- Increase the PHP Memory Limit
- Check File Permissions
- Ask Your Host (Report it to your hosting provider)
- Check the Database Connection
- Reinstall WordPress
Turn On Debugging
Once you’ve gotten your web files safely backed up, it’s time to get into the nitty gritty of resolving the 500 Internal Server Error.
As there could be a wide range of causes for this error message, the first step is to turn on debugging mode.
In debugging mode, WordPress will provide more specific warnings and error messages that help to clarify the cause of the 500 Internal Server Error.
Turning on debugging mode will require a tiny bit of coding. Before you begin, you’ll want to have a fail-safe if things go wrong.
When editing a WordPress core file like the wp-config file, the best practice is to create a backup version.
To do this, first create a copy of the wp-config file.
To find the file, enter cPanel and navigate to Files > File Manager > public_html > wp-config.php.
Next, rename the file by changing its extension. In this case, you would be changing .php to .anything.
Most webmasters like to use .old but it doesn’t matter what you choose.
If things go wrong for any reason, all you have to do is first delete the modified file, then rename the copied file. In this case, that would mean turning your new wp-config.old file back to the default wp-config.php.
Once you have safely created a backup wp-config file, you’ll be ready to turn on debugging mode in WordPress.
Right click on the wp-config folder, to edit it within cPanel.
When the file opens up, scroll to the bottom of the page, where you can add the following line of code:
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', TRUE);
Once done, don’t forget to save the change.
Once you’re done debugging, you will need to reverse this. No need to delete the code. Just replace true with false like so:
define('WP_DEBUG', false);
Again, remember to save the change.
Switch Themes
A lot of the time, when things go wrong with a WordPress website, it is down to plugin/theme upgrade issues or compatibility issues. The first step in troubleshooting a 500 internal server error will usually start by changing your theme to one of the default WordPress themes like Twenty Twenty-One.
To do this, navigate over to Appearance > Themes. Click on the theme you would like to install, in this case, Twenty Twenty-One, and activate it.
If the problem persists, you will progress to troubleshooting your plugins.
Deactivate All Plugins
To check if the problem is with your plugins, follow a similar process. In your WordPress backend, navigate to Plugins on the side menu.
Deactivate all plugins and reactivate them one after the other to see which one triggers the problem. Test between each activation to see which plugin causes the 500 error to reappear.
As soon as the error reappears, deactivate the plugin you just activated and test again. If the error disappears, you have found the cause of the error.
If neither changing your theme or plugin resolves the situation, the problem might lie a little deeper under the hood.
Check the .htaccess File
The .htaccess file is a file that controls much of how your users interact with your website. Web servers generally run on two types of software. These are NGINX and Apache, with Apache being the more commonly used.
If your web server runs on Apache, your website will need a .htaccess file that provides instructions to Apache on how access to your site should be granted.
Errors in .htaccess configuration are a common cause of 500 internal server errors.
To check if the error is caused by the .htaccess file, change its name from .htaccess to something else to prevent the server from recognizing and loading it. If this resolves the error message, then you should repair the file or create another.
The .htaccess file can be found in the public_html folder.
To find and edit it, you can either use cPanel or FTP. If you’re using cPanel, you will need to navigate to File Manager > public_html.
Right click on the .htaccess file and select Edit.
Below is what a .htaccess file should look like. If yours is in need of repair, simply paste in this code via FTP/SFTP or access it through the cPanel File Manager.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
If you cannot find a .htaccess file in your public_html folder, you may need to create a new one. This is easy to do.
At the top left-hand corner of your screen, click on + File. In the pop up that appears, enter .htaccess as the New File Name.
Once created, copy and paste in the code above and save the file as .htaccess..
Increase the PHP Memory Limit
When browsers send requests to a web server, some PHP memory is required to execute this process. Sometimes, a 500 Internal Server error occurs because of scripts that use up too much memory before they complete.
To fix this, you can increase the amount of PHP memory available for processing requests while you contact your web hosting service to help with finding and fixing the troublesome scripts.
There are a number of ways to increase PHP memory for a WordPress website as you will see below. By now, you will have learned how to work in these files. All you’ll have to do is add in little bits of code here and there.
Edit the .htaccess file
You’ve already learned how to work with .htaccess earlier. To increase the PHP memory allocation for your website, simply open the .htaccess file in a text editor, and add the following code:
php_value upload_max_filesize 64M
php_value post_max_size 64M
Then save the change.
You can also use 128M or 256M if required. There is no guarantee that this will work as some web hosts limit memory from the server side, which ignores the setting you’re changing. Not all hosts do this, which is why we suggest it here.
Edit the Wp-Config File
You can find the wp-config file for your website in cPanel or using FTP. Download the wp-config file from your root directory, open it in a text editor, and add the following code:
define(‘WP_MEMORY_LIMIT’, ’64M’);
ini_set(‘post_max_size’, ’64M’);
ini_set(‘upload_max_filesize’, ’64M’);
And save the change.
Increase Memory Allocation in PHP.ini
A final method of increasing your WordPress websites’s PHP memory allocation is by increasing the memory allocation from the PHP.ini file. The PHP.ini file is a PHP configuration file that controls things like execution time, memory and much more.
If you’re using shared hosting you won’t be able to edit your PHP.ini file. If you have dedicated hosting or a virtual hosting plan, you might be able to edit your PHP.ini file in cPanel.
Ordinarily, you will find the PHP.ini file stored in your root folder. You can also edit this file manually.
In both cases, first find the PHP.ini file in the root directory of your WordPress installation. As we advised earlier, to create a safety net in case things go wrong, copy a new version of the PHP.ini file and save the old one with a different extension such as .old.
Next, download the file and open it in a text editor. Paste in the configuration values you would like to use on your website–in this case, if you’re trying to set the memory limit at 128 megabytes, you would include a line of code like this:
memory_limit = 128M
If you’re working in cPanel, simply save this file and delete the backup. If you’re working with FTP, upload the file and that should fix the issue.
Check File Permissions
Another possible cause of an internal 500 error is a file permissions error. File permissions determine who can read, write and execute functions within your WordPress code.
Incorrect permissions are a security threat but they can also lead to 500 Internal Server error messages.
If things have gone awry on your WordPress website, check your permissions files to see if the the following WordPress recommended settings are still in place:
- wp-admin: 755
- wp-content: 755
- wp-content/themes: 755
- wp-content/plugins: 755
- wp-content/uploads: 755
- wp-config.php: 644
- .htaccess: 644
- All other files – 644
To check these, you can simply right click on each file in the public_html folder in cPanel or in your FTP client, and click on change permissions.
If the contents of your version of this file look different, update it with these settings. As always, don’t forget to save your changes.
Ask Your Host
If you have tried all the previous steps and nothing has worked, you may need to report the error to your hosting service provider. They will usually be able to accurately troubleshoot any errors, and in many cases, will carry out fixes themselves.
Be sure to provide as many details as you can including what actions you suspect may have triggered the 500 Internal Server Error, as well as the steps you have taken to resolve it.
There are a couple more steps you may take if you would like to complete the troubleshooting process on your own.
Check the Database Connection
An error in establishing a database connection is another potential cause of an internal 500 server error. This can happen for a number of reasons. For example, incorrect database login credentials, a corruption of your WordPress database, or a problem with the server.
A broken database connection will be a little more challenging to resolve as you will not have access to either the front or back end of your WordPress installation.
To resolve this, you will need to access your WordPress files via FTP/SFTP or cPanel.
Next, check the php.ini file to confirm that your database login credentials are correct. As we mentioned earlier, you won’t be able to access this file if you’re using a shared hosting plan. If you are, you may need to ask your hosting service for some help.
If you aren’t, you can find the php.ini file in your cPanel, in the public_html folder.
These credentials include:
- MySQL name
- MySQL database surname
- MySQL database password
- My SQL hostname
You should have these credentials recorded somewhere from when you first set up WordPress.
If these are in order, the problem may lie with a corrupted database.
Fixing a corrupt database is straightforward. Be aware, though, that in rare circumstances, this process can cause you to lose data.
You will have to enable database repair mode by adding a bit of code into the wp-config.php file:
define('WP_ALLOW_REPAIR', true);
You can do this from your cPanel or via FTP.
Navigate to the public_html folder in file manager, right click on the wp_config file and click Edit.
Scroll down to the bottom of the page–right before the line that says “That’s all, stop editing! Happy blogging.”, and paste in the code above.
Once this is done, visit the following address in your browser:
https://yourdomain.com/wp-admin/maint/repair.php
Once here, you will have the options of enabling a WordPress repair, or optimizing the database.
We recommend that you choose the repair option.
Reinstall WordPress
Reinstalling WordPress or reverting to an error-free version of your WordPress installation is a method that will help you get around the problem without really solving it.
If you have gone through all the previous methods without success, you may want to priorities getting your site back online and this method is the quickest way of doing it.
If you opt for this path, then be sure to build your website the right way from the beginning. Properly configured websites are less likely to run into 500 Internal Server errors, at least, not frequently!
How to Prevent a 500 Internal Server Error
There isn’t an exhaustive list of things that could cause a 500 Internal Server error but the following tips should help you avoid the majority of them
These are our top three tips:
Use a Reliable Hosting Service
As you might have realized by now, a lot of what could go wrong with a 500 Internal Server error may happen on your web server, out of your control.
Simply choosing a web hosting provider that provides faster servers and more bandwidth can help. You should also choose a web host that offers responsive and technically skilled customer support.
Use Properly Coded Themes and Plugins
Not all WordPress themes and plugins are built using high-quality code or industry best practices. Astra is, which is why it is so popular with web developers around the world. For a smooth WordPress experience, try Astra!
Use a Staging Environment
Major changes to your website should be tested in a staging environment before being implemented on your live site.
This will allow you to catch any issues with themes of plugins before they have a chance to cause a 500 Internal Server error on your live site.
Final Thoughts
The 500 Internal Server error can cause much distress but now you know what to do when it happens.
Like most technical troubleshooting, it’s largely a case of a process of elimination, trying a fix, testing it and then moving on to another. It’s slow and steady but it works!
Remember to create regular backups of your WordPress website and don’t wait for issues to crop up before you do!
With the steps we’ve shown you, you will overcome any instances of this frustrating error like a pro.
Recommended Articles:
- How to fix the err connection refused error
If you have had to deal with a 500 Internal Server error in the past, let us know which of these solutions worked for you. We’d love to hear what tips you might have!
Are you seeing a 500 internal server error in WordPress?
The internal server error is one of the most common WordPress errors. Since the error doesn’t give any other information, many beginners find it quite frustrating.
In this article, we will show you how to easily fix the 500 internal server error in WordPress.
Here is a quick overview of the topics we’ll cover in this article.
- What is The 500 Internal Server Error?
- What Causes The Internal Server Error in WordPress?
- Video Tutorial
- Fixing The 500 Internal Server Error in WordPress
- Clear WordPress and Browser Cache
- Checking for Corrupt .htaccess File
- Increasing the PHP Memory Limit
- Deactivate All WordPress Plugins
- Switch to a Default WordPress Theme
- Re-uploading Core Files
- Enable Debug Logs in WordPress
- Ask your Hosting Provider
What is The 500 Internal Server Error?
The 500 internal server error is a common web server error. It is not specific to WordPress websites and can happen with any website.
The 500 in the error message is technically an HTTP error code. Looking up this code will only show its standard description.
“500 Internal Server Error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.“
This is a generic catch-all error message which means that the server was unable to assign a better more helpful error message when it encountered the issue.
The error page looks different depending on which web server software (Nginx or Apache) your website is using and which browser you are using.
Here is how the Apache error page may look.
It may look different if you are using Nginx and Google Chrome.
It will also look different if Google chrome is unable to find an error page to display:
For beginners, this can be incredibly frustrating. There is no clue or message that would point them in the right direction to quickly fix it.
Asking how to fix an internal server error is like asking your doctor how to fix the pain you’re experiencing without telling them where the pain is.
However, if we know the common causes that trigger this error, then we can try fixing them one by one to resolve the error without breaking anything.
What Causes The Internal Server Error in WordPress?
Internal server error in WordPress is often caused by a corrupt .htaccess file, poorly coded plugins, or your active WordPress theme.
Other possible causes of the internal server error in WordPress that we know of are: PHP memory limit or corrupt core WordPress files.
In some conditions, the internal server error may only show up when you are trying to access the WordPress admin area while the rest of the site works fine.
That being said, now let’s take a look at how to go about troubleshooting the internal server error in WordPress.
Video Tutorial
Subscribe to WPBeginner
If you prefer written instructions, then continue reading.
Fixing The 500 Internal Server Error in WordPress
Before you begin troubleshooting, make sure that you have a complete WordPress backup of your website on hand.
If you have access to the WordPress admin area, then you can a WordPress backup plugin to create a complete backup of your website. We recommend using Duplicator to handle this.
On the other hand, if you don’t have access to the WordPress admin area, then you can manually create a WordPress backup using phpMyAdmin and an FTP client.
After that, you can follow the following steps to troubleshoot and fix the internal server error on your website.
Clear WordPress and Browser Cache
Browsers and your WordPress caching plugins can sometimes mistakenly store a cached copy of an error page.
The easiest way to fix this is by first clearing your browser cache.
After that, if you have access to the WordPress admin area of your website, then you can empty the WordPress cache by visiting your caching plugin’s settings page.
For details, see our tutorial on how to clear WordPress cache.
Checking for Corrupt .htaccess File
The .htaccess file is a server configuration file that is also used by WordPress to set up redirects.
One of the most common causes of the internal server error is the corrupt .htaccess file.
The easiest way to fix this is by simply visiting the Settings » Permalinks page in the WordPress admin area and then clicking on the ‘Save Changes’ button without making any changes at all.
WordPress will now try to update your .htaccess file or generate a new one for you. You can now visit your website to see if this has resolved the internal server error.
If you can still see the error, then you need to make sure that WordPress was able to generate or write to the .htaccess file.
Sometimes, due to file and directory permissions, WordPress may not be able to create or write to your .htaccess file.
You can now try to manually replace the .htaccess file. First, you need to login to your website using FTP or the File Manager app under your hosting account control panel.
Next, you need to rename your main .htaccess file to something like .htaccess_old. This lets you keep the file as a backup, but WordPress won’t recognize it.
To rename the .htaccess file, you will need to login to your site using FTP or File Manager app in your hosting account’s cPanel dashboard.
Once you are connected, the .htaccess file will be located in the same directory where you will see folders like wp-content, wp-admin, and wp-includes.
Simply, right-click on the .htaccess file and rename it to .htaccess_old.
Next, you need to create a new .htaccess file.
Inside your site’s root folder, right-click and then select ‘Create new file’ option in your FTP client or File Manager app.
Name this new file .htaccess and click OK to save it.
Now, this .htaccess file is currently empty and you need to add default WordPress rewrite rules to it.
Simply right-click on the file and then select View/Edit in your FTP client or File Manager app.
The empty file will open in a plain text editor like Notepad or TextEdit. Now, you need to copy and paste the following code inside it.
# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
This code is the default rule set used by WordPress. Don’t forget to save your changes and upload the file back to the server.
You can now visit your website to see if this has resolved the internal server error.
If it did, then give yourself a pat on the back because you fixed the internal server error.
Important: Before you move on with other things, make sure that you go to Settings » Permalinks page in the WordPress admin area and click the save button without making any changes. This will regenerate the .htaccess file for you with proper rewrite rules to ensure that your post pages do not return a 404 error.
If checking for the corrupt .htaccess file solution did not work for you, then you need to continue reading this article.
Increasing the PHP Memory Limit
Sometimes the internal server error can happen if a script is consuming all the PHP memory limit.
The easiest way to increase the PHP memory limit is by editing the wp-config.php file. Be careful when you do this if you’re a beginner. You want to follow these instructions carefully because even small mistakes in WordPress core files can break your site.
To begin, simply connect to your WordPress website using an FTP client or the File Manager app under your hosting account control panel.
You’ll find wp-config.php file inside the main folder of your website. Right-click on it and select ‘Download.’ This will ensure that you have a backup of the file in case something goes wrong.
When you’ve saved that, you can right-click on it and select ‘View/Edit.’
Inside the wp-config.php file, you need to add the following code just above the line that reads ‘That’s all, stop editing! Happy publishing’.
define( 'WP_MEMORY_LIMIT', '256M' );
For more details, see our tutorial on how to increase PHP memory limit in WordPress.
If you are seeing the internal server error only when you try to log in to your WordPress admin or upload an image in your wp-admin, then you should increase the memory limit by following these steps:
- Create a blank text file on your computer and name it php.ini
- Paste this code in there: memory=256MB
- Save the file
- Upload it into your /wp-admin/ folder using FTP
If increasing the memory limit fixed the problem for you, then you have only fixed the problem temporarily. You still need to find the cause that is exhausting your memory limit.
This could be a poorly coded plugin or even a theme function. We strongly recommend that you ask your WordPress web hosting company to look into the server logs to help you find the exact diagnostics.
If increasing the PHP memory limit did not fix the issue for you, then you are in for some more troubleshooting.
Deactivate All WordPress Plugins
If none of the above solutions worked for you, then this error is most likely being caused by a specific plugin installed on your website.
It is also possible that it is a combination of plugins that are not playing nice with each other.
If you can access the WordPress admin area of your website, then you can simply go to the plugins page and deactivate all WordPress plugins.
However, if you are unable to access the WordPress admin area, then you can deactivate all WordPress plugins using FTP.
Simply connect to your WordPress website using an FTP client or the file manager app under your hosting account control panel.
Once connected, navigated to the /wp-content/ folder and rename the plugins folder to plugins.deactivated.
WordPress looks for plugins in the plugins folder. If the plugins folder is not found, then it will automatically deactivate all plugins.
You can now try visiting your website to see if this resolved the internal server error on your website.
To restore all your plugins, you can simply rename the plugins.deactivated folder back to plugins.
Your plugins will now be restored but they will still be deactivated.
You can now activate plugins one by one and visit your website to figure out which plugin is causing the internal server error.
For more details, see our guide on how to deactivate all WordPress plugins without WP-Admin.
If deactivating all plugins didn’t fix the internal server error on your website, then continue reading.
Switch to a Default WordPress Theme
One possible cause of the internal server error could be some code in your WordPress theme.
To find out if this is the case, you need to switch your theme to a default WordPress theme.
If you have access to the WordPress admin area, then simply go to the Appearance » Themes page. If you have a default theme already installed then you can simply click on the Activate button to switch theme.
If you don’t have a default theme installed, then you can click on the Add New button at the top and install a default theme (Twenty Twenty-Three, Twenty Twenty-Two, etc).
Now in case you don’t have access to the WordPress admin area, you can still switch to a default theme.
Simply, connect to your WordPress website using an FTP client and navigate to the /wp-content/ folder.
Right-click to select the themes folder and download it to your computer as a backup.
Next, you need to delete the themes folder from your website. Once it is deleted, go ahead and create a new themes folder.
Your new themes folder will be completely empty which means you don’t have any WordPress themes installed at the moment.
Next, you need to visit the WordPress themes directory and download a default WordPress theme to your computer.
Your browser will then download the theme as a zip file to your computer.
Locate the file on your computer and then unzip it. Windows users can unzip file by right-clicking on it and then selecting Extract All. Mac users can double-click on the zip file to extract it.
You’ll now see a folder containing your WordPress theme.
Switch back to your FTP client or File Manager up and upload this folder to the empty themes folder.
Once uploaded, WordPress will automatically start using the default theme.
You can now visit your website to see if this resolved the internal server error.
If this didn’t work, then you can reupload your WordPress themes from the backup or switch back to the theme you were using.
Don’t worry there are still a few more things you can do to fix the error.
Re-uploading Core Files
If the plugin and theme options didn’t fix the internal server error, then it is worth re-uploading the /wp-admin/ and /wp-includes/ folders from a fresh WordPress install.
This will NOT remove any of your information, but it may solve the problem in case any file was corrupted.
First, you will need to visit the WordPress.org website and click on the Download button.
This will download the WordPress zip file to your computer.
Go ahead and extract the zip file. Inside it, you will find a wordpress folder.
Next you need to connect to your WordPress website using an FTP client.
Once connected go to the root folder of your website. It is the folder that has wp-admin, wp-includes, wp-content folders inside it.
In the left column open the WordPress folder on your computer.
Now you need to select all files inside the wordpresss folder and upload them to your website.
Your FTP client will now transfer those folders to your server.
It will ask you whether you would like to overwrite the files. Select ‘Overwrite’ and then select ‘Always use this action’.
Your FTP client will now replace your older WordPress files with new, fresh copies.
If your WordPress files were corrupted, then this step will fix the internal server error for you.
Enable Debug Logs in WordPress
WordPress comes with a built-in system to keep logs for debugging.
You can turn it on by using the WP Debugging plugin. For more details, see our guide on how to install a WordPress plugin.
Once activated, the plugin will turn on debugging logs on your WordPress website.
If you don’t have access to the admin area of your WordPress website, then you can turn on debugging by adding the following code to your wp-config.php file.
define( 'WP_DEBUG', true); define( 'WP_DEBUG_LOG', true);
Once you have turned on debug logs, you can view these logs by using an FTP client and navigating to the /wp-content/ folder.
You can open the debug log file in a text editor and it will show you a list of errors and warnings that occur on your website.
Some of these errors and warnings can be harmless incidents that may not need fixing. However, if you are seeing an internal server error on your website then these may point you in the right direction.
Ask your Hosting Provider
If all methods fail to fix the internal server error on your website, then it is time to get some more help. Contact your web hosting support team and they will be able to check the server logs and locate the root cause of the error.
If you want to continue troubleshooting on your own, then see our ultimate WordPress troubleshooting guide for beginners.
We hope this article helped you fix the internal server error in WordPress. You may also want to see our complete list of the most common WordPress errors, and our guide on how to choose the best web hosting provider.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
Seeing a 500 internal server error where your website should be is enough to throw anyone into a panic. When your website goes down, you lose out on potential traffic and sales. If it’s offline for a while, it can also negatively impact your Search Engine Optimization (SEO) efforts.
Fortunately, there are plenty of ways to go about fixing this error. Many of these solutions are fairly straightforward, and you don’t need a lot of technical know-how to start troubleshooting.
In this guide, we’ll cover what the 500 internal server error in WordPress is and discuss some potential causes. Then we’ll give you 10 tips to help you get your website back in working order.
- Back up your website.
- Try reloading the page.
- Clear your browser cache.
- Access your error logs.
- Check for the “Error Establishing a Database Connection.”
- Look for permission errors.
- Increase your PHP memory limit.
- Check for problems with your .htaccess file.
- Look for coding or syntax errors in your CGI/Perl script.
- Ask your web host about potential server issues.
Let’s get started!
Dealing with the WordPress Internal Server Error?
Avoid troubleshooting when you sign up for DreamPress. Our friendly WordPress experts are available 24/7 to help solve website problems — big or small.
What Is the 500 Internal Server Error?
The 500 internal server error is frustratingly nonspecific. When the error occurs, you usually don’t get many details about it. In fact, you might not receive any information at all.
The 500 error is a generic issue that isn’t specific to WordPress. Chances are you’ve seen it before during your internet explorations. Despite the name, it doesn’t necessarily mean that something is wrong with your server. It could be an issue with your website or browser.
If you do see this error on your site, you’ll want to get it fixed as quickly as possible. A 500 error can impact your SEO if allowed to linger. If your site is crawled while it’s offline, there’s a chance that Google may interpret the error as an issue with your website.
This error can also hurt your User Experience (UX) and give visitors the impression that you’re unprofessional. Not only can a poor UX affect the way Google ranks your site, but it can cause you to lose customers as well. After all, you can’t do business if your site isn’t accessible.
A wide variety of situations can result in the 500 error, making it a bit of a chore to sort out. Potential causes of the 500 internal server error in WordPress include:
- Plugin compatibility issues
- Exhausted PHP memory limit
- Corrupted files
- Coding or syntax errors
The fact that the error message itself tends to be vague doesn’t help. Fortunately, you can solve many of these issues on your own with a bit of know-how.
Variations on the 500 Internal Server Error
Depending on your operating system, browser, and the cause of the error, there are variations in how it will appear. For example, if a database connection can’t be established, you might see something like this:
A plain white screen, sometimes referred to as the White Screen of Death (WSoD), can indicate a 500 internal server error.
Also, many site owners have the option to customize their 500 error messages. So you might see this error in many different forms.
How to Fix the 500 Internal Server Error in WordPress (10 Tips)
Now that you’ve had an introduction to the 500 internal server error, it’s time to discuss how to resolve it. Let’s take a look at ten tips you can use to fix this issue in WordPress.
1. Back up your website.
Before tinkering under the hood, it’s always smart to make a backup of your website. If DreamHost hosts your site, you can take advantage of our one-click backup feature. You can also create a manual backup if you prefer.
To make a complete backup, you’ll need to save copies of your WordPress files as well as your databases. You can back up your site’s files using a Secure File Transfer Protocol (SFTP) client such as FileZilla.
Once you’re connected to your server, navigate to the WordPress files you want to save. These files include the WordPress core installation, plugins, themes, images, and more. To save the files, simply right-click on them and select Download.
Now you’ll need to back up your database, which you can do by logging into phpMyAdmin. Select the database you want to download from the left-hand panel, and then click on the Export tab.
You’ll then need to choose between a “Quick” or a “Custom” export. The Quick export will likely work just fine unless you need to manage more advanced options.
Click on the Go button, and your download should start. Once your website is safely backed up, you can get to work on fixing that 500 error.
2. Try reloading the page.
Let’s start with the best-case scenario. Some situations that cause a 500 internal error clear up on their own within a few minutes. For example, if you’ve just made changes to a plugin or theme, or if your host is experiencing unusually heavy traffic, you may see a server error. If this is true in your case, you’re in luck, as a simple page reload should get things back to normal.
Therefore, the first thing to try is simply waiting a minute or two, during which the error will hopefully resolve itself. Then you can try reloading the page by pressing F5 or (command + R if you’re using a Mac).
3. Clear your browser cache.
Another potential server error fix that’s quick and easy is clearing your browser cache. It’s possible the cache became corrupted, which would cause problems when attempting to access websites.
First, you might check Down For Everyone Or Just Me. This will determine whether there’s a widespread problem or you’re the only one experiencing difficulties.
If you’re alone in your 500 error frustration, the problem may be your browser. Try accessing your site from a different browser. If an alternative works, it’s a sign that the issue is with your cache.
In Google Chrome, you can clear your cache by pressing Ctrl + Shift + Delete. Alternatively, you can click on the three vertical dots in the top-right corner, followed by More tools > Clear browsing data.
Be sure to check the Cached images and files box. Then click on the Clear data button.
In Firefox, you can clear the cache using the Ctrl + Shift + Delete keyboard shortcut. This will open the Clear Recent History window. In the Time range to clear drop-down menu, select Everything. Check the Cache box, and then click on OK.
In Safari, you can navigate to the History menu item and choose Clear History. Keep in mind that this will delete everything, including cookies and visited pages.
Once you’ve cleared your browser cache, you can attempt to access your website again. If you’re still seeing the 500 internal server error, it’s time to move on to more involved fixes.
4. Access your error logs.
Your site’s error logs may provide insight into what’s causing the 500 error. Depending on your host, these logs may be cycled quite often, so you’ll want to take a look as soon as possible.
You can check your error logs by accessing your site’s files via SFTP and looking for the /logs directory. Next, select the site that’s experiencing the error. You may see several directories at this point. You’ll want to check the one with the most recent date.
You can view the log by downloading it and opening it with your preferred text editor. Hopefully, your error logs will provide you with some additional context for the 500 error.
Another option is to enable the WordPress debug log. You can do this by connecting to your site via SFTP and opening your wp-config.php file. Within it, look for the following line:
define('WP_DEBUG', false);
Once you find it, replace it with the following:
define( 'WP_DEBUG', true ); define( 'WP_DEBUG_DISPLAY', false ); define( 'WP_DEBUG_LOG', true );
This will create a debug.log file, which you can find under the /wp-content/ directory. Just be sure to change the WP_DEBUG value back to “false” when you’re done troubleshooting.
5. Check for the ‘Error Establishing a Database Connection.’
If there’s been a problem establishing a database connection, not only will your site be offline for visitors, but you won’t be able to access the WordPress admin dashboard either. There are a few possible causes of this:
- Incorrect database login credentials
- A corrupted WordPress database
- A corrupted WordPress installation file
Let’s start with incorrect login credentials, as this is a common cause of the database connection error. If you’re a DreamHost user, you can find your database credentials in your panel. However, if you use a different host, you’ll likely follow a similar procedure.
Navigate to MySQL Databases and find the one that corresponds to your website under the Database(s) on this server section. Here, you’ll find your database name under the Database heading. The username is listed under the Users Access column.
Alt-text: Where to find your MySQL username in DreamPanel.
To find the password, click on the username. On the next screen, scroll down and click on the Show button next to the password field.
Next, you’ll compare these credentials to those in your wp-config.php file. You can access this file in your site’s main directory via SFTP. Once you have the file downloaded, open it and verify that the information under MySQL Settings matches what you found in your panel.
Next, if your database is corrupted, you can quickly repair it through phpMyAdmin. Log in and click on your database in the left panel. Select all of the tables in the database, and then choose the Repair table option from the drop-down menu.
Finally, let’s look at how to handle a corrupted WordPress installation file. Start by downloading a new copy of WordPress and unzipping the file. You’ll need to delete the wp-content folder and the wp-config-sample.php file.
Upload the rest of the files to your site via SFTP, overwriting any existing ones. You now have a brand new, uncorrupted WordPress installation. You’ll also want to clear your browser cache before checking your website again.
6. Look for permission errors.
If any of your files have permissions set incorrectly, you may see the 500 internal server error as a result. Again, you can check and change these permissions using SFTP.
Right-click on any file and select File permissions to open a new dialogue window. In this window, you can check and, if necessary, set new permissions for the file.
Typically, you’ll want to set files to “644” and directories and executables to “755”. However, you may want to check with your host if you’re unsure about the correct values.
7. Increase your PHP memory limit.
Another reason you might see the 500 internal server error is if you’ve exceeded your server’s PHP memory limit. There are several ways to increase your limit, and they all involve using SFTP.
Before you try increasing your memory limit, you may want to start by seeing what it’s currently set to. You can do this through the WordPress admin dashboard. Keep in mind that, with some variations of the 500 error, you won’t be able to access the dashboard. If that’s the case, you may have to skip this step.
From your WordPress dashboard, navigate to Tools > Site Health. Click on Info at the top of the screen, and scroll down to the Server section. You should see your PHP memory limit there.
To increase the PHP memory limit, there are a few files you can edit. One is your .htaccess file, typically located in your site’s root directory. Open the file and add the following code:
php_value memory_limit xxxM
You can replace the “xxx” with your desired amount of memory. Usually, 256M is plenty.
You can also increase your memory limit by editing your php.ini file. You should be able to find this file in your root directory. If not, you can go ahead and create one. Add or update its code to the following:
memory_limit = xxxM
Another option is to add in the following code at the top of your wp-config.php file:
define('WP_MEMORY_LIMIT', 'xxxM');
If this resolves the 500 error, your next task will be to figure out what is causing the memory limit exhaustion. It could be a problematic plugin or theme. You might consider reaching out to your host for help on finding the exact server diagnostics.
8. Check for problems with your .htaccess file.
Your .htaccess file is one of the core WordPress files. It contains rules for your server, so it could contribute to a 500 internal server error.
If your .htaccess file has become corrupted, you’ll want to go ahead and create a fresh one. Start by logging into your site via SFTP and finding your .htaccess file. Rename the file to .htaccess_old.
Now, create a new .htaccess file in your text editor and paste in the following:
# BEGIN WordPress RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END WordPress
Go ahead and upload your newly created .htaccess file. Then refresh your site in your browser, and check to see whether the error message is showing.
9. Look for coding or syntax errors in your CGI/Perl script.
If you’re running Common Gateway Interface (CGI) scripts, any coding errors you’ve made could result in a 500 error. To unearth potential issues with your CGI scripts, log into your site using Secure Shell Access (SSH).
Once you’ve logged in, you can troubleshoot your CGI with this command:
[server]$ ./cgi_name.cgi
The terminal should return a general error message and the line number the culprit is located on. From there, you can work your coding magic!
When working with CGI, there are a few best practices to keep in mind to avoid problems. First, it’s wise to use a plain text editor to ensure that you maintain ASCII format. When you upload scripts, you should also be able to select ASCII mode in your FTP client.
Finally, if necessary, upload to the cgi-bin directory on your server. Then you can double-check your files’ permissions once you have them uploaded.
10. Ask your web host about potential server issues.
If all else fails, there may be a server issue, which only your host can confirm. Unfortunately, if your host’s server is experiencing a problem, you may have to wait out some website downtime.
If you’re a DreamHost client, you can check the DreamHost Status page. This resource provides you with information on all of our services.
If you run into any problems while trying to repair the 500 internal server error, you can always reach out to our tech support team. They’re ready and waiting to lend you a hand! If you’ve followed the tips in this guide, you’ll have plenty of valuable information for the technician.
Get Content Delivered Straight to Your Inbox
Subscribe to our blog and receive great content just like this delivered straight to your inbox.
Additional WordPress Error Reading
Want to learn more about fixing common WordPress errors? We’ve put together several tutorials to help you if you encounter any other issues.
- How to Fix Syntax Errors in WordPress
- How to Fix the WordPress Not Sending Email Issue
- How to Fix the Error Establishing Database Connection in WordPress
- How to Fix WordPress Error 404 Not Found
- How to Fix the Sidebar Below Content Error in WordPress
Let’s Get Your WordPress Website Back on Track
While having to sort out a 500 internal server error isn’t exactly fun, it’s also not as painful as you might imagine. With a little patience and the tips we’ve provided, you should be able to make some progress on getting your website back online.
You can start small by refreshing your page and clearing your browser cache. Then you might want to move onto more involved fixes, such as increasing your PHP memory limit. If you’re not able to resolve the error on your own, DreamHost’s award-winning tech support is just a click away.
When you do run into errors, it’s easier to get back up and running when you have a reliable hosting provider. DreamPress is fast, secure WordPress hosting with powerful features to help make your site a success!