Ошибка 500 apache2

Уровень сложности
Простой

Время на прочтение
3 мин

Количество просмотров 2.7K

Одна из самых популярных и при этом не всегда логирующаяся ошибка apache2 — «Internal Server Error». В этой статье разберу возможные причины и решения из интернета и личного опыта. Иногда эта ошибка весьма не очевидна.

Все ситуации описаны для операционной системы Ubuntu Linux 22.10.

Ну и, конечно, первое, что вы должны сделать это попробовать перезапустить службу.

sudo systemctl restart apache2

Если это не помогло, то двигаемся дальше.

1. Конфигурация

1.1. Ошибка конфигурации веб-приложения

Прежде всего рекомендую сделать запрос к вашему сайту локально, прямо с сервера.

curl localhost:80

Если вы не видите «Internal Server Error», а видите html страницу, то 99% проблема в файлах конфигурации и настройках доступа.

Проверьте файл: /etc/apache2/sites-available/your_app.conf
где your_app.conf — название вашего файла конфирурации, либо стандартный conf файл — «000-default.conf»

Как он выглядит:

/etc/apache2/sites-available/your_app.conf

/etc/apache2/sites-available/your_app.conf

Строка «Require ip 127.0.0.1» говорит, о том, что разрешено подключение только с локального хоста.

Решение: замените строку «Require ip 127.0.0.1» на «Require all granted»
Так же «Require all granted» должна быть в /etc/apache2/apache2.conf

/etc/apache2/apache2.conf

/etc/apache2/apache2.conf

1.2. Старый конфигурационный файл

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

Решение:
1. Выключаем стандартный файл конфигурации
2. Включаем свой
3. Перезагружаем apache2

a2dissite 000-default.conf 
a2ensite your_app.conf 
systemctl restart apache2 

2. Права доступа

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

2.1. Владелец файлов

Файлы вашего проекта не принадлежат пользователю www-data.

Папка проекта (your_project) не принадлежит пользователю www-data

Папка проекта (your_project) не принадлежит пользователю www-data

Решение:

sudo chown -R www-data:www-data your_project/

P.S. Случается так, что apache2 при установке не создаёт пользователя www-data, в этом нет ничего страшного, можно обойтись и без его создания. Права отлично функционируют и сайт работает.

2.2. Права файлов

Ошибка так же может возникать когда владелец установлен верно, но всё равно не имеет доступа к файлам из-за настроек прав доступа.

Решение:

sudo chmod -R 755 your_project/

2.3. Веб-приложение работает с файлами системы

«Internal Server Error» возникает, когда ваше веб-приложение взаимодействует с файлами системы у которых нет прав на исполнение. Звучит также странно как есть на самом деле, почему я не могу читать файлы у которых есть право на чтение? До сих пор не понимаю. Но проблема эта решается, если выдать файлам право на исполнение.

Решение:

sudo chmod -R 777 your_project/files/

3. Ошибка в коде вашего веб-приложения

Также частая ситуация, когда apache2 настроен правильно, но всё равно возникает эта нелогирующаяся ошибка «Internal Server Error», тогда следует проследить отрабатывает ли вообще ваше приложение.

Например, если оно не может подключиться к базе данных, то вы, всё равно, увидите «Internal Server Error». Стоит проверить верный ли пароль и есть ли доступ к базе данных. А возможно, что просто веб-приложение запустилось раньше базы данных, в этом случае поможет простая перезагрузка apache2.

Если ваше приложение взаимодействует с внешним ресурсом, и он оказывается не доступен или привышен лимит ожидания ответа, то вы снова увидите «Internal Server Error».

4. Переустановка apache2

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

sudo apt update
sudo apt install --reinstall apache2

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

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

  • Проблемы с плагинами и темами. Если вы используете WordPress или аналогичную CMS, ошибка 500 может появиться после обновления или изменения плагина или темы.

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

  • Модули Node.js. Если у вас есть сайт на основе Node.js, обновление модулей может вызвать внутреннюю ошибку сервера 500.

  • Довольно часто вредоносный код, внедряемый на ваш сайт, приводит к ошибке 500.

  • Несовместимый модуль. Загрузка несовместимого модуля PHP или Apache вызывает ошибку 500.

P.S. Надеюсь, кому-то помог. Удачи.

Many times Apache gives 500 Internal Server Error due to various reasons. In the article, we will look at what is 500 internal server error, why do you get this error message and how to fix 500 Internal Server Error in Apache localhost, CPanel other systems like Ubuntu, CentOS, Windows.

Apache gives 500 Internal Server Error when there is a server-side error that prevents Apache from processing a request and returning a proper response. This can be due to various reasons such as faulty code, inadequate file permissions, missing files referenced in code, etc. There are multiple ways to fix 500 internal server error in Apache.

Bonus Read : How to Install mod_deflate in Apache

How to Fix 500 Internal Server Error in Apache

Here are the steps to fix 500 internal server error in Apache on localhost, CPanel, PHP, Ubuntu, and other systems.

1. Hard Refresh the Page

The simplest way to fix 500 internal server error in Apache is to simply refresh the page. Sometimes you may be requesting a page when the server is being restarted. In such cases, you will get 500 internal error.

Sometimes, the server may be overloaded with requests and doesn’t have resources to process your request.

In both these cases, you can do a hard refresh to force the browser to connect to server and download the latest website content. You can do this by pressing

  • Windows: Ctrl + F5
  • Mac: Apple + R or Cmd + R
  • Linux: F5

Bonus Read : How to Fix 504 Gateway Timeout Error in Apache

2. Examine Server Logs

Many times, you get 500 internal server error only for one page or a few pages but not all pages on your website. So it is important to check your server log to find the requests causing this issue.

Every server log records the requested URL along with the returned response. Among the most recent requests, look for the ones that have returned 500 response code.

This will tell which script is causing the issue. Once you have identified the script, open your browser and request this page again to confirm that it is indeed raising the error in server log.

3. Examine your script

Next, check if your script is working properly.

Is your script in the right place? Have you named it correctly? Is your URL mapping/routing referencing the right script?

If your script refers any file, then are the file paths correct? If they refer any function/program, have you referenced them correctly ?

Bonus Read : How to Fix 502 Bad Gateway Error in Apache

4. Check File/Folder Permissions

Did you modify any file/folder permission recently? Did you create a new file/folder in your code?

If so then you might be seeing 500 internal server error due to wrong file/folder permissions. Typically, files should have 644 user permission while folders should have 755 permission. You can use FileZilla (Windows) or CHMOD (Linux) to change file permissions.

Look at the permissions of other files/folders in your code and update the permission for your file/folder accordingly.

Bonus Read : How to Increase Request Timeout in Apache

5. Check .htaccess file

If you have set up URL rewrites or URL redirection, then you may have used .htaccess file. Make sure you have setup mod_rewrite correctly.

Also use a third-party tool to check URL rewrite syntax, and ensure they are correct.

Bonus Read : How to Enable mod_rewrite in Apache

6. Increase Script Timeout

If your Apache server depends on another external script/function to process a request and it times out, then Apache will return 500 Internal Server error.

So increase the timeout values of those external scripts so that they maintain the connection and return a proper response.

Hopefully, the above tips will help you fix 500 internal server error in Apache.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!

Related posts:

  • About Author

mm

This is an Ancient answer from 2013, back when PHP was new and security wasn’t an issue:

Here in the future it’s a security risk to dump errors to screen like this. You better not be doing this in any production setting.

Why are the 500 Internal Server Errors not being logged into your apache error logs?

The errors that cause your 500 Internal Server Error are coming from a PHP module. By default, PHP does NOT log these errors. Reason being you want web requests go as fast as physically possible and it’s a security hazard to log errors to screen where attackers can observe them.

These instructions to enable Internal Server Error Logging are for Ubuntu 12.10 with PHP 5.3.10 and Apache/2.2.22.

Make sure PHP logging is turned on:

  1. Locate your php.ini file:

    el@apollo:~$ locate php.ini
    /etc/php5/apache2/php.ini
    
  2. Edit that file as root:

    sudo vi /etc/php5/apache2/php.ini
    
  3. Find this line in php.ini:

    display_errors = Off
    
  4. Change the above line to this:

    display_errors = On
    
  5. Lower down in the file you’ll see this:

    ;display_startup_errors
    ;   Default Value: Off
    ;   Development Value: On
    ;   Production Value: Off
    
    ;error_reporting
    ;   Default Value: E_ALL & ~E_NOTICE
    ;   Development Value: E_ALL | E_STRICT
    ;   Production Value: E_ALL & ~E_DEPRECATED
    
  6. The semicolons are comments, that means the lines don’t take effect. Change those lines so they look like this:

    display_startup_errors = On
    ;   Default Value: Off
    ;   Development Value: On
    ;   Production Value: Off
    
    error_reporting = E_ALL
    ;   Default Value: E_ALL & ~E_NOTICE
    ;   Development Value: E_ALL | E_STRICT
    ;   Production Value: E_ALL & ~E_DEPRECATED
    

    What this communicates to PHP is that we want to log all these errors. Warning, there will be a large performance hit, so you don’t want this enabled on production because logging takes work and work takes time, time costs money.

  7. Restarting PHP and Apache should apply the change.

  8. Do what you did to cause the 500 Internal Server error again, and check the log:

    tail -f /var/log/apache2/error.log
    
  9. You should see the 500 error at the end, something like this:

    [Wed Dec 11 01:00:40 2013] [error] [client 192.168.11.11] PHP Fatal error:  
    Call to undefined function Foobar\byob\penguin\alert() in /yourproject/
    your_src/symfony/Controller/MessedUpController.php on line 249
    

В данной статье мы рассмотрим наиболее вероятные причины возникновения ошибки 500 “Internal Server Error”.
Причины указаны в порядке вероятности возникновения.

  1. Использование в файлах .htaccess недопустимых на нашем хостинге конструкций, например Options
    -MultiViews
    или php_value и php_flag. Вы можете открыть файл .htaccess текстовым редактором и
    найти строки, в начале которых используются указанные конструкции. Найденные строки можно удалить
    или добавить # в начале. Файл .htaccess может находиться в корневом каталоге вашего сайта — на
    том же уровне, что и файлы index.php или index.html или robots.txt.

  2. Скрипт пытается получить больше памяти, чем ограничено параметром memory_limit. Обычно
    достаточно увеличить этот параметр в панели
    управления. Увеличивать стоит постепенно, с шагом в
    16 — 32 Мб, пока ошибка не пропадет. Новые настройки PHP вступают в силу в течение 3-5 минут.

  3. В панели управления или в php.ini включены не совместимые друг с другом расширения php.
    Например, одновременное включение eaccelerator и APC, либо eaccelerator и XCache почти наверняка
    будет приводить к ошибке Segmentation Fault и, как следствие, к ошибке Internal Server Error на
    сайте.

  4. Если вы редактировали какие либо файлы сайта в ОС Windows, то при сохранении в файл могли
    добавиться не совместимые с unix-форматом символы переноса строки. Для корректной работы необходимо
    использовать совместимые с unix-форматом переносы строк. Например, в
    Notepad++ этот параметр можно настроить в меню “Правка” -> “Формат
    конца строк” -> “Преобразовать в UNIX-формат”.

  5. Слишком долгая работа скрипта (может быть связано, например, с выгрузкой товаров на сайте, либо
    другими долгими запросами). Если веб-сервер не получает никакого ответа от скрипта в течение 120
    секунд, скрипт считается зависшим и его работа принудительно завершается с выдачей ошибки 500.
    Изменить это ограничение в индивидуальном порядке на виртуальном хостинге нельзя. В качестве решения
    вы можете запускать выполнение скрипта, разбив данные на части, либо через
    cron либо напрямую через
    ssh-соединение.

  6. Скрипт возвращает HTTP-заголовки, которые веб-сервер не может распознать и не понимает как интерпретировать.

Включение лога ошибок apache

Однозначно определить источник ошибки поможет включение лога ошибок. Для этого потребуется зайти в
панель управления https://panel.netangels.ru/virtualhosts/ , слева от названия сайта кликнуть на
иконку с тремя горизонтальными полосками и выбрать “Журнал ошибок”. Когда ошибки возникнут, то в
домашнем каталоге на сервере появится файл вида sitename.ru-error.log, где sitename.ru — имя сайта,
для которого вы включили лог ошибок.

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

Так же может быть полезно включить лог php ошибок поставив
галочку напротив пункта error.log и нажав кнопку сохранить. Лог ошибок будет сохранен в файле
log/php-errors.log.

Are the websites in your server giving ‘500 internal server error’ all of a sudden? In our role as Outsourced server support specialists for web hosts, this is one commonly encountered errors in Apache web server.

A PHP upgrade, Apache recompilation, permission or ownership changes, anything can trigger a 500 error in a website. The impact of the error can vary based on the cause that triggered it.

See how we help web hosting companies

Today, we’ll discuss the probable causes for ‘500 internal server error’ in Apache and how to resolve them.

What causes ‘500 internal server error’ in Apache?

‘500 internal server error’ is a very broad error, and to pin-point the actual cause of the issue, it is very vital to observe the Apache/PHP error logs and to detect the recent changes made in the server.

With our years of experience handling web servers for a wide range of web hosting companies, we’ve come across several causes that can trigger this error, such as:

  • A PHP upgrade or Apache recompilation that went wrong – Due to compatibility issues or unsupported modules in Apache/PHP, the websites can throw 500 errors.
  • Errors in the format or content of PHP or CGI scripts – A code error, unsupported format or wrong path to the binary, can generate errors in the scripts.
  • Settings in .htaccess or other config files that are not supported – For instance, servers that run SuPHP do not support php_flag or php_value directives in .htaccess files.
  • Server or file system restrictions such as log file size, SELinux restrictions or time out settings for executing a script.
  • Errors related to the PHP config file – Any unsupported or invalid setting in php.ini can lead to 500 errors.
  • Incorrect permissions and ownership for the files – In SuPHP, files and folders should be under user ownership, folders should have 755 permissions, non-scripts files need 644, PHP Scripts require 600 and 755 is needed for CGI and shell scripts.
  • A web server or PHP module that is not working fine – A corrupt php.ini file, a module that is no longer supported, etc. can also lead to 500 internal server errors in Apache.

[ You don’t have to lose your sleep over server errors. Our expert server specialists are online 24/7/365 to help you fix all server errors. ]

How to resolve ‘500 internal server error’ in Apache

When we come across customers who complain about 500 errors, we first check whether the error affects just one site or every site in the server. Depending on the impact of the error, we debug further.

If only one domain it affected, it can be pin-pointed to the specific script error or permission issues. If multiple domains show 500 error, it could be due to some server wide setting change or update.

From the Apache error logs, we detect the script or the module that is the culprit. We follow a systematic debugging approach, which helps us resolve the error in no time.

As improperly planned Apache updates or recompilation can cause server wide errors or PHP module to malfunction, we take proper caution and do adequate testing to avoid a web site downtime for our customers.

[ Use your time to build your business. We’ll take care of your servers. Hire our server support experts to maintain your servers secure and stable 24/7 . ]

At Bobcares, our 24/7 server specialists constantly monitor all the services in the server and proactively audit the server for any errors or corruption in them.

With our systematic debugging approach for service or other software errors, we have been able to provide an exciting support experience to the customers.

If you would like to know how to avoid downtime for your customers due to errors or other service failures, we would be happy to talk to you.

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Понравилась статья? Поделить с друзьями:
  • Ошибка 500 adobe muse
  • Ошибка 500 102
  • Ошибка 50 средство dism не поддерживает
  • Ошибка 4ло на крузаке моргает
  • Ошибка 4е8а бмв