Http error 500 apache2 ubuntu server

I'm getting 500 Internal Server errors when I try to make an HTTP POST to a specific address in my app. I've looked into the server logs in the custom log directory specified in the virtual hosts ...

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
    

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

I’m currently trying to get php , apache and mysql up and running on Ubuntu. I’ve recently switched from Windows to Ubuntu to learn. But i’m facing a bit of a problem. When the code is correct the file gets executed properly in browser, where as when there is an syntax error, instead of showing the error in browser it throws an error as shown.

HTTP 500 Error

I’ve checked my php setting via phpinfo() and its as follows.
phpinfo

I think error reporting is enabled, and I’ve tried reading similar other questions on the various threads,but they didn’t really help me out. They pointed out that i need to verify that .htaccess file is in good shape. I’m not exactly sure how do i verify that, can anyone help me out? I’ve also tried changing directory permissions to 777 and 755 but that didn’t help either. Any idea as to how can i fix it?

asked Feb 8, 2017 at 18:15

FreeKrishna's user avatar

2

You display_errors directive is set to no.

To fix this:

  1. Edit /etc/php/7.0/apache2/php.ini and set:

    ; display_errors
    ;   Default Value: On
    ;   Development Value: On
    ;   Production Value: Off
    
    ; display_startup_errors
    ;   Default Value: Off
    ;   Development Value: On
    ;   Production Value: Off
    
    
    #to 
    
    ; display_errors
    ;   Default Value: On
    ;   Development Value: On
    ;   Production Value: On
    
    ; display_startup_errors
    ;   Default Value: On
    ;   Development Value: On
    ;   Production Value: On
    
  2. Restart your apache with:

    sudo systemctl restart apache2
    
  3. To have the same behaviour on the cli edit the /etc/php/7.0/cli/php.ini

  4. To set this value locally add this to a .htaccess file in the server root: /var/www/html

Do

    vim .htaccess

Press i

Type the following:

    # Displaying php errors
    php_flag display_errors on
    php_value error_reporting 6143

Press

Esc
:x
Enter

Note:

Mine was php version 7.0. Change to your particular version. And in your image both local and master values are both set to Off so:

  1. step 1 will change the master value, and

  2. step 4 will change the local value.

answered Feb 8, 2017 at 19:25

George Udosen's user avatar

George UdosenGeorge Udosen

35k12 gold badges97 silver badges119 bronze badges

2

You just need to add following lines of code to your PHP file for temporary configuration

error_reporting(E_ALL);
ini_set('display_errors', 1);

vanadium's user avatar

vanadium

76.8k6 gold badges107 silver badges166 bronze badges

answered Sep 10, 2018 at 5:37

Rahul Hirve's user avatar

you can fix now this way

1 : /etc/php/7.0/apache2/php.ini

2: ; error_reporting
Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
Development Value: E_ALL
Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
3 : sudo systemctl restart apache2

answered May 7, 2019 at 6:22

Rajendra Singh Rathore's user avatar

1

Содержание

  1. Apache2 500 internal error
  2. clop1000
  3. JohnRambo
  4. clop1000
  5. clop1000
  6. clop1000
  7. JohnRambo
  8. clop1000
  9. Apache CGI — ошибка 500
  10. ЛОР — последее, куда обращаюсь за советом.
  11. Так что, копайте, что там у вас в этом CGI.
  12. Ошибка 500 internal server error Nginx
  13. Как исправить 500 internal server error Nginx
  14. 1. Ошибка в скрипте PHP
  15. 2. Превышено время выполнения или лимит памяти
  16. 3. Неверные права на файлы
  17. Выводы
  18. Похожие записи
  19. Оцените статью
  20. Об авторе
  21. 2 комментария к “Ошибка 500 internal server error Nginx”

Apache2 500 internal error

clop1000

New member

Установил апач и 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 модуль или в конфиге апача.

New member

JohnRambo

New member

clop1000

New member

clop1000

New member

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

clop1000

New member

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

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

Options Indexes FollowSymLinks
AllowOverride All
Require all granted

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

JohnRambo

New member

clop1000

New member

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

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

Источник

Apache CGI — ошибка 500

ЛОР — последее, куда обращаюсь за советом. Только если уже другие ресурсы бессильны. Виртуальный хост сервера Apache на Ubuntu выдает ошибку 500 при исполнении CGI скриптов. На localhost все скрипты работают.Вот лог ошибки:

ЛОР — последее, куда обращаюсь за советом.

Права на все файлы и папки стоят 777

Кто владелец /media/data/HTML/www/cgi/? Выложи конфиг куда-нибудь.

Premature end of script headers

Означает, что скрипт запустился, но либо упал с сегфолтом, либо вернул какую-то фигню.

Так что, копайте, что там у вас в этом CGI.

ЛОР — последее, куда обращаюсь за советом.

Это чтобы не задавать тут «хэлловорлдные» вопросы, которые, как правило, возникают у всех, кто только начинает что-то осваивать.

Так что, копайте, что там у вас в этом CGI.

скрипт рабочий 100%. Он работает в localhost, ели вы об этом

О, там же у тебя логи пишутся, посмотри в них 😉

А кто будет разрешать запуск CGI, Пушкин?

что посмотреть в логах то. вы меня запутали ps да, кстати владелец — рут

это я тоже пробовал — не помогает. может я куда то не туда пихаю этот код?

tail -f /var/log/httpd/*

Запускаем CGI и смотрим, что пишут логи.

это я тоже пробовал — не помогает. может я куда то не туда пихаю этот код?

Запросто. Кстати, доступ 777 с владельцем-рутом — нехорошо.

На каком ЯП CGI-то?

логи я приводил ведь.

Почему 777 под рутом не хорошо? на локальной машине вроде не страшно

Короче, пишите правильный конфиг. Перезапускайте апач. Приводите выхлоп.

куда надо прописать?

в логах пишет одно и тоже, нет смысла приводить

Ну, например, у меня так работает (/etc/httpd/conf/httpd.conf):

Кстати, а html-ки то виртуальный хост отдает?

эти же директивы будут аналогично работать в sites-available? хтмлки хост отдает и даже пхпшки, а вот cgi не хочет

755 на каталог и cgi-скрипты

FUUUUUUCK. что то с самими файлами на диске или с диском, потому что с переносом виртуального хоста на /home все заработало! изза чего это может быть.

Значит все-таки права криво раздал в апаче

Или /media/data подмонтирован с noexec =)

// в общем, телепаты вовсю работают!

ТС! Ну объясни же ты: зачем пихать корень веб-сервера в /media ?

Ты не в курсе, для чего эта директория?

Да нет, дело не в апаче совсем, как выяснилось. На диске запрещается исполнение файлов всем не только через апач или ещё что-то не так , я пока не разобрался. наверно что-то с монтированием

🙂 Опять мой libastral.so не подвел

/media/data монтируется через файл fstab вот так

Для сменных накопителей: флешек, USB-HDD и т.п.

Оно еще и на ntfs! Вот это жесть.

А что, есть принципиальная разница , куда кидать корень локального сервера для тестирования страничек? На нтфс он только, чтобы к файлам был доступ и через винду тоже. А куда тогда правильно монтировать жесткие диски? Где же тогда параметры прав при монтировании? rw? Буковка x к ним ничего не дает

Это ntfs! Так что можно забыть о нормальных правах доступа.

Как вариант, если уж так хочется «черезжопия», можно создать образ ext2-раздела на этом ntfs-разделе и держать файлы там (монтировать его через loop-device).

да нет, не хочется черезжопия. на корень сервака в нтфс я забил уже.

Источник

Ошибка 500 internal server error Nginx

При разработке веб-сайтов и веб-приложений можно столкнуться с ошибкой 500 internal server error. Сначала она может испугать и ввести в заблуждение, поскольку обычно веб-сервер выдает более конкретные ошибки, в которых указана точная причина проблемы, например, превышено время ожидания, неверный запрос или файл не найден, а тут просто сказано что, обнаружена внутренняя ошибка.

Но не все так страшно и в большинстве случаев проблема вполне решаема и очень быстро. В этой статье мы разберем как исправить ошибку Internal server error в Nginx.

Как исправить 500 internal server error Nginx

Дословно Internal server error означает внутренняя ошибка сервера. И вызвать её могут несколько проблем. Вот основные из них:

  • Ошибки в скрипте на PHP — одна из самых частых причин;
  • Превышено время выполнения PHP скрипта или лимит памяти;
  • Неправильные права на файлы сайта;
  • Неверная конфигурация Nginx.

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

1. Ошибка в скрипте PHP

Мы привыкли к тому, что если в PHP скрипте есть ошибки, то сразу же видим их в браузере. Однако на производственных серверах отображение сообщений об ошибках в PHP отключено, чтобы предотвратить распространение информации о конфигурации сервера для посторонних. Nginx не может отобразить реальную причину ошибки, потому что не знает что за ошибка произошла, а поэтому выдает универсальное сообщение 500 internal server error.

Чтобы исправить эту ошибку, нужно сначала понять где именно проблема. Вы можете включить отображение ошибок в конфигурационном файле php изменив значение строки display_errors с off на on. Рассмотрим на примере Ubuntu и PHP 7.2:

sudo systemctl restart php-fpm

Затем обновите страницу и вы увидите сообщение об ошибке, из-за которого возникла проблема. Далее его можно исправить и отключить отображение ошибок, тогда все будет работать. Ещё можно посмотреть сообщения об ошибках PHP в логе ошибок Nginx. Обычно он находится по пути /var/log/nginx/error.log, но для виртуальных доменов может настраиваться отдельно. Например, смотрим последние 100 строк в логе:

tail -n 100 -f /var/log/nginx/error.log

Теперь аналогично, исправьте ошибку и страница будет загружаться нормально, без ошибки 500.

2. Превышено время выполнения или лимит памяти

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

Также подобная ошибка может возникать, если на сервере закончилась свободная оперативная память.

Если же отображение ошибок отключено, мы получаем error 500. Обратите внимание, что если время ожидания было ограничено в конфигурационном файле Nginx, то вы получите ошибку 504, а не HTTP ERROR 500, так что проблема именно в php.ini.

Чтобы решить проблему увеличьте значения параметров max_execution_time и memory_limit в php.ini:

sudo vi /etc/php/7.2/php.ini

max_execution_time 300
memory_limit 512M

Также проблема может быть вызвана превышением других лимитов установленных для скрипта php. Смотрите ошибки php, как описано в первом пункте. После внесения изменений в файл перезапустите php-fpm:

sudo systemctl restart php-fpm

3. Неверные права на файлы

Такая ошибка может возникать, если права на файлы, к которым обращается Nginx установлены на правильно. Сервисы Nginx и php-fpm должны быть запущены от имени одного и того же пользователя, а все файлы сайтов должны принадлежать этому же пользователю. Посмотреть от имени какого пользователя запущен Nginx можно командой:

nginx -T | grep user

Чтобы узнать от какого пользователя запущен php-fpm посмотрите содержимое конфигурационного файла используемого пула, например www.conf:

sudo vi /etc/php-fpm.d/www.conf

В моем случае это пользователь nginx. Теперь надо убедится, что файлы сайта, к которым вы пытаетесь обратиться принадлежат именно этому пользователю. Для этого используйте команду namei:

namei -l /var/www/site

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

sudo chown nginx:nginx -R /var/www/site

Этой командой мы меняем владельца и группу всех файлов в папке на nginx:nginx. Добавить права на чтение для всех пользователей для каталога можно командой chmod. Например:

sudo chmod o+r /var/www/

Далее все должно работать. Также, проблемы с правами может вызывать SELinux. Настройте его правильно или отключите:

Выводы

В этой статье мы разобрали что делать если на вашем сайте встретилась ошибка 500 internal server error nginx. Как видите проблема вполне решаема и в большинстве случаев вам помогут действия описанные в статье. А если не помогут, напишите свое решение в комментариях!

Похожие записи

Нет похожих записей.

Оцените статью

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

2 комментария к “Ошибка 500 internal server error Nginx”

Чушь.
1. header(«http/1.1 500 Internal Server Error») ;
И логи не помогут.
2. Если скрипт превышает лимиты, то, вероятнее всего, в коде что-то не так. Бесконечный цикл, например. С ним, кстати, и увеличение этих лимитов не спасёт.

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

инициировать такую ошибку можно элементарно. например, отключаем сервис PostgreSQL и вуаля. Welcome home, dear!

Источник

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

NOTE: This question has been resolved! Please see below for the solution in my case if you are having a similar issue!

Background:

This is a PHP/MySQL based, database driven application that makes heavy use of AJAX, and nearly all requests to the server occur this way. The requests are GET requests in this instance, and the server is responding via JSON. The user works inwards through the data set returning finer and finer results. The application is stable, and in production.

I have the ability to debug this on 3 platforms: My development laptop (OSX), an in-house Ubuntu server, and the production Ubuntu server.

Each Ubuntu server is running a MySQL server, and a copy of Apache.

My development laptop connects to the MySQL server running on our in-house Ubuntu server, and runs it’s own Apache server.

Both Ubuntu servers are 9.10, x64, fully up-to-date via the official sources, Apache 2.2.12, PHP 5.2.10.

And now the fun part:

The application returns results correctly in all cases except one subsection of the data set. Requests for data within this subsection always return a 500 instead of a result set. The subsection in question is merely a query to return results based on known IDs. The records are known to exist, and contain no corrupt data.

I have debug logging turned on for Apache, and E_ALL set for PHP (logging to file). When the 500 occurs, I see the following in Apache’s error.log (x’s for masking):

[Sun Aug 01 15:43:54 2010] [debug] mod_deflate.c(615): [client 192.168.1.28] Zlib: Compressed 0 to 2 : URL /apps/xxxx/connectors/details_lookup.php, referer: http://xxxx.xxxx.local/apps/xxxx/

This implies a lack of data. However, there are no errors logged to PHP’s error log whatsoever. At the same time, I can return results elsewhere in the data set with no issues.

So you might be thinking «The problem must be with the database.»

However, when I use my development laptop (and it’s own copy of Apache) to connect to the same MySQL server on our in-house network, I can run the request that generates the 500 with no errors at all.

So when I run the application on my Apache server on my laptop, everything’s cool. When I perform the same request against the same data within the same database on the same database server but instead using that server’s local copy of Apache, fail.

I’m utterly baffled. Any help would be greatly appreciated at this point.

Одна из наиболее распространенных ошибок, возникающих при просмотре веб-страниц, — это «500 Internal Server Error». Это сообщение указывает на то, что на веб-сервере возникли технические проблемы.

В этой статье объясняется, что означает ошибка 500, почему вы получаете код HTTP 500 и как устранить эти ошибки.

Что такое ошибка HTTP 500

Каждый раз, когда вы открываете веб-страницу, ваш браузер отправляет запрос на сервер, на котором размещен сайт, который возвращает запрошенные данные и код ответа. Коды состояния HTTP-ответа указывают, был ли запрос успешным или нет.

Ответы делятся на пять классов. Коды в диапазоне от 500 до 599 указывают на ошибку сервера.

Код состояния HTTP 500 — это общий ответ об ошибке, который возвращается сервером, когда другой код ошибки не подходит. Это может быть вызвано рядом проблем, которые не позволяют серверу выполнить запрос.

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

  • Перезагрузите браузер или попробуйте использовать другой. Шансы, что страница загрузится при обновлении браузера, невелики, но все же стоит попробовать.
  • Попробуйте очистить кеш браузера. Если страница, на которой отображается ошибка 500, кэшируется, после очистки кеша браузер запросит новую версию страницы.
  • Вернуться позже. Тем временем веб-мастер может устранить проблему с сервером.
  • Свяжитесь с владельцами веб-сайтов. Последний оставшийся вариант — связаться с лицом, ответственным за обслуживание веб-сайта.

Устранение неполадок 500 Ошибка

Ошибка 500 Internal Server Error может быть вызвана рядом различных причин. Вот самые распространенные:

  • Проблема с разрешением. Когда веб-сервер не имеет разрешений на доступ к файлам сайта, он может выдать ошибку HTTP 500. Решением этой проблемы является рекурсивное изменение разрешений для файла веб-сайта .
  • Ошибка синтаксиса .htaccess . Если вы используете Apache в качестве веб-сервера, то, скорее всего, у вас есть файл .htaccess в корневом каталоге вашего сайта. Неверный синтаксис или несуществующая директива модуля может привести к ошибке 500.
  • Проблема, связанная с базой данных. Ошибка HTTP 500 также может быть вызвана неверной информацией о сервере базы данных или поврежденной базой данных.
  • Проблемы с плагинами и темами. Если вы используете WordPress или аналогичную CMS, ошибка 500 может появиться после обновления или изменения плагина / темы.
  • Проблемы с сервером. Поврежденная файловая система или исчерпанная память могут привести к ошибке 500.
  • Модули Node.js. Если у вас есть сайт на основе Node.js, обновление модулей может вызвать внутреннюю ошибку сервера 500.
  • Взломанный сайт. Довольно часто вредоносный код, внедряемый на ваш сайт, приводит к ошибке 500.
  • Несовместимый модуль. Загрузка несовместимого модуля PHP или Apache вызывает ошибку 500.
  • Тайм-аут внешнего ресурса. Если сервер взаимодействует с внешней службой и если эти службы недоступны, сервер отобразит сообщение об ошибке 500.

Лучший способ определить, почему произошла ошибка 500, — это проверить файлы журнала сервера. Расположение файлов журнала зависит от вашего дистрибутива Linux и веб-сервера. Наиболее распространенные места для Apache и Nginx следующие:

/var/log/apache2/error.log
/var/log/httpd/error_log
/var/log/nginx/error_log

Если ваше приложение построено на Node.js, проверьте журналы Node.js.

Обычно журнал сервера содержит подробную информацию об ошибке, которая поможет вам определить и исправить ошибку.

Выводы

Ошибка 500 Internal Server Error — это общий код состояния HTTP, означающий, что что-то пошло не так с веб-сервером, на котором размещен сайт, который вы посещаете.

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

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»;

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

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

  • Http error 414 что значит
  • Http error 499 что это
  • Http error 413 альфа банк
  • Http error 498
  • Http error 484

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

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