Apache2 ошибка 500

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
    

1.Refresh the Page

The first thing to do when you encounter this error is wait a moment and then refresh the page. Sometimes this error is caused when a service restarts, and you happen to catch it at exactly the wrong time. If the problem persists after you refresh the page, continue troubleshooting.

2.Check Your Server Logs

  • Your first stop should be your website’s error logs. On a Linux server, the default location for the main website error log is /var/log/httpd/error_log.
  • If you have multiple websites hosted on your server, they will likely have their own error logs. The location of these log files will be specified in the site’s Apache configurations. Typically these are located in the website’s /logs/ directory.
  • If the error log is large, it can be difficult to find the correct line. If you know that a particular script is causing the error, you can search the file for this script name by using the command:
    • more /var/log/httpd/error_log | grep [file name]
      This will return any lines which have the file name in them.
  • If you are not sure what is causing the error, you can follow the error log in one window and watch it being generated. First, in your SSH session, use the command:
    • tail -f /var/log/httpd/error_log
      Without closing the SSH session, go to a web browser and refresh the page to generate the 500 error again. You should see the error appear in the log file.
  • You can also view the last 10 lines in the error log with the command:
    • tail -20 /var/log/httpd/error_log
      Once you find the error, copying and pasting it into Google will often yield helpful results.

3.Check Permissions

An HTTP 500 error can be caused by a permissions problem with your website’s files or folders. Check the permissions on all of your main folders and scripts. Most Perl and CGI files need to have their permissions set to 755.

To check the permissions of files on a Linux system, connect via SSH to your server and go to the directory where the files are kept. Use the ll command to list all files and file details.

The first block of letters lists the file’s permissions. There are three permission levels:

Read (r)
Write (w)
Execute (x)
The permissions are shown in groups of three:

Group 1: Owner
Group 2: Group
Group 3: World (everyone)

4.Changing Permissions

To change the permissions for a file, you need to use the chmod command, along with the numerical value of the permissions level you want to set. The most common permissions levels are:

7: Read, write, and execute (rwx)
5: Read and execute (r-x)
0: None (—)
Most scripts will require read/write/execute permissions for the owner, and read/execute permissions for group and world. To set this on a file, use the command:

chmod 755 [filename]
If you are still receiving an error when you run your script, try setting it to global read/write/execute permissions for testing purposes. To set this on a file, use the command:

chmod 777 [filename]
This permissions level can be risky, because it allows anyone to rewrite your file. Once you have finished troubleshooting, be sure to set the file back to the correct permissions.

5.Examine Your Scripts

If your website relies on scripts (such as Perl or CGI files), there are a number of things that can go wrong. Always check the file permissions first. If those are correct, examine the scripts themselves.

Are they in the right place, and named correctly? Verify that the scripts have not been moved, deleted, or renamed by accident.

Are the file paths correct? Many scripts will require other files and programs in order to run. For example, if you have a Perl script, it will start with the path to Perl. You can use the which command to find the path to Perl (or any other programming language or command) with the command:

which perl

Do the scripts have permission to run in the folder where they are located? You may want to find a simple test script to check this.

Be sure your test script is in the same language as the one you are troubleshooting, and uses the same file extension. For example, if you are having trouble with a Python script named myfile.py, search for a Python test script, and give the file a .py file extension. Using a Perl test script, or a Python test script that ends in .cgi won’t be effective as a test.

Was the script recently edited in a word processing program like Microsoft Word or Wordpad? CGI programs and other scripts should only be edited with a text editor like Notepad. To fix this problem, find a fresh copy of the script, and use a text editor like Notepad (for Windows) or BBEdit (for Mac).

6.Check the Apache Files

An HTTP 500 error can be caused by a problem with your Apache configurations. If you have scripts or CGI programs which are generating a 500 error, check to make sure they have permission to run in the directory where they are located.

Apache will not allow programs to execute by default. Permission must be given in either an .htaccess file in the directory where the program runs, or in the website’s main Apache configuration file.

7.Granting Permissions With an .htaccess File

You can grant executable permissions on a directory-by-directory basis using an .htaccess file.

Note: because the file name begins with a period, the file will be hidden from a basic ls search from the command line. To list the files in the directory including any which begin with a period, use the command:

ls -la
Either edit the existing file, or create one in the directory, if none exists. You can also create this file in Notepad on your desktop computer, and upload it to your website with FTP.

The file will need to have this line:

Options +ExecCGI
You will also need a line that will tell Apache how to run scripts written in Python, PHP, Perl, etc. Customize this line to add the extension your files are using (.py, .php, .pl, etc.).

AddHandler cgi-script .cgi .py .php .pl

8.Is the .htaccess File Being Read?

If you have an .htaccess file which is set up correctly, but you are still getting an HTTP 500 error, the problem might be that the .htaccess file is being ignored.

In order for the .htaccess file to work, Apache will need to be configured to allow it to run.

Check the website’s main Apache configuration file. For the main domain on a server, this will typically be:

Ubuntu and Debian: /etc/apache2/apache2.conf
CentOS 7: /etc/httpd/conf/httpd.conf

For other domains being hosted on the server, the location and name of the file will vary depending on how the domain was set up.

Edit this main configuration file and find the block which pertains to the directory where you are adding an .htaccess file. For example, the default document root for the main directory will probably be:

<directory “=”” var=”” www=”” html”=””>

Inside this block, look for the AllowOverride configuration. Set this to:

AllowOverride All

After making changes to the main Apache configuration file, restart Apache for the changes to take effect:

Ubuntu and Debian: use the command service apache2 restart.
CentOS 7: use the command systemctl restart httpd.

9.Timeout Errors

If you have scripts which call external networks or resources, an HTTP 500 error can be caused when those connections time out, usually because the resource is unreachable. Check your external resources to be sure they are accessible.

  • Author
  • Recent Posts

Rajesh Kumar

Mentor for DevOps — DevSecOps — SRE — Cloud — Container & Micorservices at Cotocus

Join my following certification courses…
— DevOps Certified Professionals (DCP)
— Site Reliability Engineering Certified Professionals (SRECP)
— Master in DevOps Engineering (MDE)
— DevSecOps Certified Professionals (DSOCP)
URL — https://www.devopsschool.com/certification/

My Linkedin — https://www.linkedin.com/in/rajeshkumarin
My Email — contact@DevOpsSchool.com

Rajesh Kumar

В данной статье мы рассмотрим наиболее вероятные причины возникновения ошибки 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-заголовки, которые веб-сервер не может распознать и не понимает как интерпретировать.

Хранение логов ошибок

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

Логи хранятся в папке ~/sitename.ru/log, где
sitename.ru — название Вашего сайта.

В данном примере мы рассматриваем сайт на php. Нас интересуют следующие файлы:

error.log — лог ошибок apache. Отвечает за хранение ошибок, полученных в результате работы веб-сервера

php-errors.log — лог ошибок php. Отвечает за хранение ошибок, полученных в результате работы php-файлов.

Лог сайта на python

Логи для сайта на python будет хранится в файле — wsgi-runlog/current

Лог сайта на node

Логи для сайта на node будет хранится в файле — node-runlog/current

Просмотр логов ошибок по SSH

Для того чтобы посмотреть логи ошибок можно воспользоваться SSH-консолью.
Для этого перейдите на страницу Вашего сайта.

10.PNG

Выберите вкладку “Файлы” и нажмите на ней кнопку “Терминал”.

11.PNG

В открывшемся окне введите команду.

cd log

12.PNG

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

ls -la

13.PNG

Чтобы вывести информация из файла введите команду.

cat error.log

Просмотр логов ошибок c помощью файлового менеджера

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

10.PNG

Выберите вкладку “Файлы” и нажмите на ней кнопку “Файловый менеджер”.

11.PNG

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

14.PNG

Для прочтения любого файла два раза нажмите на нужный файл.

Инструкция для Виртуального хостинга

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

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

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

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

Установил апач и php при попытки зайти на 127.0.0.1 пишет Internal Server Error 500

в логе /var/log/error.log

[client 127.0.0.1:38930] AH00027: No authentication done but request not allowed without authentication for /. AstraMode requires authentication.

Как это победить
1) Правильным способом. Как использовать эту пресловутую Astra аунтификацию. Что эт такое вообще?
2) как это выключить в «хакерском режиме»? Пологаю что нужно выключть какой то PAM модуль или в конфиге апача.

oko


to clop1000
Primo, какая версия ALSE? 1.6? Судя по логу, она самая…
Secundo, в документации (Руководство администратора на ту же ALSE 1.6) есть все ответы на ваши вопросы. В частности, раздел 6…
Хотел процитировать, да раздумал, — научитесь читать оф.документацию самостоятельно…

2) как это выключить в «хакерском режиме»? Пологаю что нужно выключть какой то PAM модуль или в конфиге апача.

В /etc/apache2/apache2.conf установить AstraMode off
и перезагрузить службу apache

Secundo, в документации (Руководство администратора на ту же ALSE 1.6) есть все ответы на ваши вопросы. В частности, раздел 6…
Хотел процитировать, да раздумал, — научитесь читать оф.документацию самостоятельно…

А это какая из?) Там у них много руководств) Какой из pdf-ок_)

Нашел) Ruk_admin_1.pdf

А кто нибудь успешно настраивал Kerberos авторизацию?)
А то как то сложно выглядит? Есть у кого опыт?

Последнее редактирование:

Сюдаже что бы не плодить новую тему:

Как включить поддержку .htaccess?

<Directory /var/www/html/example.com/public_html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

mod_auth_kerb/5.4
И после чего caught SIGTERM, shutting down

А кто нибудь успешно настраивал Kerberos авторизацию?)

Да, сквозная аутентификация на web-сервере Apache2 работает.

Да, сквозная аутентификация на web-сервере Apache2 работает.

А можете рассказать в кратце как это работает в пактическом смысле?
Это желательно только в рамках домена ALD? (Иначе придется на сервере для каждого юзера заводить аккаунт)?
Т.е. разрешения будут на каждый файл в отдельности?
А если это PHP скрипт. он же выполняется от пользователя apache2?
Работает ли apache2 в такой конфигурации в режиме целостности отличной от нуля? (т.е. когда другие сетевые службы не очень работают?)

А вы пробовали Postgres аунтификацию настраивать? Как она работает? Для каждой строки мандатная метка?

Для сквозной аутентификации необходимо наличие домена реализованного при помощи ALD или FreeIPA.

А если это PHP скрипт. он же выполняется от пользователя apache2?

Работает ли apache2 в такой конфигурации в режиме целостности отличной от нуля? (т.е. когда другие сетевые службы не очень работают?)

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

А вы пробовали Postgres аунтификацию настраивать? Как она работает? Для каждой строки мандатная метка?

Можно в postgres пройти аутентификацию через Kerberos. Возможна установка меток на кластер, бд, схему, таблицы, на строки.

Последнее редактирование:

А как это сказывается на производительности postgres ?

Вопрос по Apache AstraMode + Kerberos + CORS
как то можно завести кроссдоменные запросы?

Ситуация такая

Если сервисы и веб на одном домене то все работает, если обращаемся к сервисами с другого домена то на запрос OPTIONS приходит ответ 401

причем указаны заголовки Origin Methods для допуска в apache и они приходят нормальными

Понравилась статья? Поделить с друзьями:
  • Apache ошибка ah00451
  • Apache ошибка 501
  • Apache the requested operation has failed ошибка
  • Apache ошибка 405
  • Apache ошибка 403