Moodle 500 internal server error

Moodle 500 internal server error is a server-side error that happens mainly due to error in the .htaccess file, wrong permissions, etc.

Moodle is one of the best open-source learning platforms. While navigating through Moodle have you got a message “500 internal server error”?

Moodle 500 Internal server error usually occurs due to the bad rewrite rules, wrong PHP settings, etc.

At Bobcares, we often fix this error for our customers who use Moodle, as a part of our Server Management Services.

Today let’s see this error in detail and discuss the ways our Support Engineers solve this for our customers.

What is Moodle 500 internal server error?

Moodle (modular object-oriented dynamic learning environment) is a free, open-source learning platform that uses PHP as a programming language. Again, 500 Internal Server Error is a server-side error. This code means that something has gone wrong on the webserver. But the server cannot specify the exact problem.

From our expertise in managing Moodle, the major possibilities for this error include:

1. Wrong rewrite rules

By default, any syntax error in the .htaccess or httpd.conf files leads to an internal server error. Similarly, the incompatible directive also causes this error. That is, it happens when we add the wrong directive in .htaccess or httpd.conf files.

2. Incorrect PHP settings

In the same way, incorrect PHP settings can also cause Moodle 500 errors.

For example, PHPsuexec is an Apache module used to increase the security of the site on the hosted system. Here the server does not support .htaccess files.

Any change in permission or ownership of the moodle directory also results in an error. Here you may also see a 403 Forbidden error.

How we fix the internal server error?

So far we have seen the reasons for the 500 error. Every reason points to bad settings in server-side files. When our customers face such an error, our Support Team begins checking by enabling debug mode.

For this, we,

  1. Log in to Moodle.
  2. Navigate to Site admnistration>>Development>>Debugging.
  3. Enable the checkbox ‘Display debug messages’.
  4. Choose the option ‘ALL: Show all reasonable PHP debug messages’ from the drop-down at ‘Debug messages’.

Enable debugging in Moodle

After making these changes our Support Engineers check for the logs. Logs give the exact reason for the error.

Now let’s see the fixes for two major causes:

1. Fixing rewrite rules

Our experts check the .htaccess or httpd.conf files and correct the syntax error.

They also check for the directive, if it was found incompatible with the server version, they fix it for our customers.

2. Correcting the PHP settings

Some customers use PHPsuexec, which does not support .htaccess file. Additionally, the error may be with permissions of the moodle directory.

So, our Dedicated Engineers set permissions of script folders to 755 using the command

chmod -R -type d 755 moodle

Here we use a php.ini file instead of a .htaccess in the moodle directory. The syntax used in the php.ini file is different from that of a .htaccess file.

[ Need help in fixing Moodle internal server error – We will fix it for you ]

Conclusion

In short, Moodle 500 internal server error is a server-side error. It happens mainly due to error in the .htaccess file, wrong permissions, etc. We saw other possible causes of errors and how our Support Engineers fixed it for our customers.

PREVENT YOUR SERVER FROM CRASHING!

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

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

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;


500 Internal Server Error

  • ◄ Username already exists
  • Deleted content packages still taking up diskspace ►

I have been using my 2.6v of Moodle for 6 month and it has never missed a beat. Today I went to log in and i got a 500 Internal Server Error.

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at webmaster@abouttrainingaustralia.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request

I have checked hy hosting account (godaddy) an there seems to be no problems there. If there is a problem within Moodle (currupt uploads, etc.) how can I get in to have a look around (is there a server-side way to access Moodle). I’m not too familir with the tech side of Moodle so please forgive my limited knowledge on the way I explain my problem. Where should I start to look for the problem?

I have 50 students studying at the moment so I need to find an answer asap. Thankyou. Terry

Terry, as I have just opened your site, it opens fine with looking like absolutely new moodle installation.

it this the site you are referring to ? «www.abouttrainingaustralia.com»

Hi Usman, Thank you so much for looking. While I was writing the post it was fixed. As luck would have it, my friend is currently attending the Moodle workshop down in Sydney (I’m from the Gold Coast) and the Moodle  trainer hopped on to the server and added a «+» in one of the files (I think it was the .htaccess file). I’m non the wiser to what caused it or how it was fixed because the trainer was so fast that it was fixed and he was off home. Thank you again for  looking. The Moodle community really rocks!

Glad it got fixed, thats what I thought in first place, problem with htaccess file as 500 errors are caused by 2 reasons only, your server down (which you had told already you are accessing it) or wrongly configured htaccess file. 

.htaccess files are often the culprit in 500 errors, which can be buggers to diagnose unless you’re a sysadmin with access to the server logs. Essentially, 500 means that something unspecified/unknown has gone wrong at the server end, which could be all sorts of things, though it’s usually unlikely to be a PHP script as, in that case, you’d either get a blank page (with PHP error reporting off) or PHP errors displayed. Quite why your .htaccess was changed is something you might have to ask your hosting company, as you don’t want your Moodle course falling over again suddenly.

If you’re not au fait with the arcane esotericism that is .htaccess, the .htaccess guide is a handy intro. 

Fred

Average of ratings: Useful (1)

 I am in the process of  installing Moodle on my site rkconsultinginc.com and I am receiving the same error 500.

I did try to check the file mentioned aboveif it was the source of error, but could not locate it. Please guide.

Hello Rupinder ,

htaccess is in yourmoodle / lib /  directory.

Hello Sakshi,

That doesn’t have anything to do with the problem. There’s a difference between htaccess (without an initial dot) and .htaccess (dot htaccess). The file you mentioned is only a template and is not an operational file.

Hello Rupinder,

It would be best to start by looking at the web server error log, as it should provide a better indication about the cause for the 500 error message.

If there’s a problematic .htaccess (dot htaccess file) it should be at your Moodle Installation Directory (MID). If you are accessing or browsing with an FTP program, check the settings to make sure that the program is configured to display hidden files, that is, those that start with a period or a dot.

— edited

As a brief reference:

The Six Most Common Htaccess Problems and How to Fix Them

      Thanks Guillermo for the advise.

    But I am still unable to locate any .htaccess file.This is the message which comes:

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error.

More information about this error may be available in the server error log.


Web Server at rkconsultinginc.com
I am somewhat f a novice..in this process.I actually did the entire set up following directions from William Rice Blog post…
But now i am stuck…can you guide.

Thanks
Rupinder
Rupinder

Hello Rupinder,

I you can’t find a .htaccess file it must be because there is none, so don’t worry about it anymore.

Now… first of all you need to know that a 500 HTML error is a very ambiguous error message and so, you need to start by opening the web server error log and look for clues about this error.

As a second step, or maybe this should have been the first, you need to provide more info about your server: OS, versions about everything: web server, database server, PHP, if it is a shared server, a VPS or a dedicated, etc. You should always, when requesting for help in a new thread, provide as much info as possible about your setup.

Another step, enable Debugging in your Moodle. If you cannot access or open your site, then set it via the config.php file.

Finally… I just went to your site (http://rkconsultinginc.com/), which you mentioned in your first post:

https://moodle.org/mod/forum/discuss.php?d=264350#p1168321

and I didn’t get any error messages… so? Are we talking about the same site? thoughtful

———

rkconsultinginc.com

My site is launching soon.

———

Given that this is not a Moodle issue, you need to see about it with your hosting provider.

Rupinder, though your site seems working fine, just for future reference, in order to see .htaccess files, you have to check (show hidden files) option in File Manager (as shown)

and you’ll find .htaccess file in your root directory (as shown below)

Hi Guillermo!

I’m facing a 500 error and this error in the server errors log. Do you have any suggestions about that? Thanks a lot. smile

Is it the htaccess?

[*] [warn] [client *] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server, referer: https://******/login/index.php

*] [error] [client *] Premature end of script headers: index.php, referer: https://****/login/index.php

Hello Filippo,

Apart from that, please do provide more info about your server.

https://moodle.org/mod/page/view.php?id=7080

The error log says:

Premature end of script headers: index.php, referer: etc.

Did you, or someone else, modify the index.php file at the login directory?

From what I saw, you seem to have some issue with the Certificate authentication process, so I’d say you need to start there.

Sorry you are right, i was hasty.

Here’s more information:

I’m sharing a linux server with other moodle installations and the requirements check gives me no error. (I can post more info from if needed)

I’ve been having issues with this error long before switching to https so i’m investingating the fastcgi issue.

About the certificate problem, where did you find it? 

Thanks a lot and sorry again for the missing informations,

F.

Hello Filippo,

The FastCGI issue is marked as a warning; the premature end of headers, as an error, so you might want to start there.

Regarding the certificate…

certificate issue

  • ◄ Username already exists
  • Deleted content packages still taking up diskspace ►

Moodle REST APIs failing intermittently and returning 500 (Internal Server Error)

Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.30-0ubuntu0.16.04.1, Copyright (c) 1999-2017, by Zend Technologies

<?php
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "php-error.log");
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
/**
 * Version details
 *
 * @package    local_lingk
 * @copyright  (C) 2018 Lingk Inc (http://www.lingk.io)
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once '../config.php';
//require_once '../lib/moodlelib.php';
// require_once($CFG->dirroot.'/lib/moodlelib.php');
require_once($CFG->libdir.'/moodlelib.php');
require_once 'src/Mandrill.php'; //Not required with Composer

global $DB, $CFG, $SESSION, $USER;

$CFG = new stdClass();
$CFG->dataroot = '/usr/src/moodle/moodledata';
$CFG->cookiename = 'MoodleSession';

$USER = new stdClass();
$USER->id        = -10;
$USER->email     = 'emailed';
$USER->firstname = 'Do not reply to this email';
$USER->username  = 'noreply';
$USER->lastname  = '';
$USER->confirmed = 1;
$USER->suspended = 0;
$USER->deleted   = 0;
$USER->picture   = 0;
$USER->auth      = 'manual';
$USER->firstnamephonetic = '';
$USER->lastnamephonetic  = '';
$USER->middlename     = ''; 
$USER->alternatename  = ''; 
$USER->imagealt       = '';
$USER->maildisplay    = 1;
$USER->emailstop      = 1;


header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Credentials: true");
header('Content-Type: application/json');
header("HTTP/1.0 200 Successfull operation");
// echo '=============+++++++';exit;
    $wsfunction = $_POST['wsfunction'];   
    // print_r($record);exit;
    // $client_id = $_POST['client_id'];
    // $client_secret = $POST['client_secret'];
    // $device_id = $POST['device_id'];
    $response = array();

I tried changing apache config and mysql config but APIs are failing intermittently. It works 2 times and fails on 3rd and sometimes succeeds thrice and fails on fourth attempt. Am I missing any configuration or moodle setting?

Hi All

I have had moodle up and running fine in a test environment.

Bur for some reason I have tried a fresh installation on a virgin sme system, the install went fine, but when a try add new users or courses etc I get error 500.

I can change themes, log  in etc.

Not sure where to start looking.

Any ideas?

Thanks in advance


Logged


antdickens:
every time you have an error, the first things to do are:
— take a look in the logs (httpd’s ones in your case)
— search the forums, the wiki, the documentation and bugzilla
— post a topic here with the error message
— file a bug (possibily) because «if it doesn’t work out-of-the-box, it’s likely a bug»

thank you


Logged


The best way to check the logs, I have found out, is to log into the Sever Manager Panel. View the log «messages». Then in a new tab, open your moodle or any problem application, recreate the problem, and then immediately refresh the log from your other tab.

I had an issue before where the log I was looking for got lost in DHCP leases and PPTP connections.


Logged

SME 8.0
Quad 6600
8gb DDR2 800
8 TB RAID 5
Dual Gigabit NIC
I Still Don’t KNOW WHAT I AM DOING. Please, don’t assume I know anything about Linux or Centos, I just know hardware


Hi

Thanks for your advice.

I have looked in the httpd log files through the sme server manager and there are no entries relating to moodle other than in the access log which does update each time I view a page, nothing about errors in that or any other http log file.

« Last Edit: July 11, 2013, 12:47:19 PM by antdickens »


Logged


search the messages log file

follow wiki advice to enable displaying of php errors


Logged


Hi

Thanks for that

It appears the problem is down to the version of PHP installed

I need to either upgrade moodle or downgrade php

Least I now know which way to head

Thanks again


Logged


please report here the exact error message, thank you


Logged


here you go

Jul 11 12:06:57 bits httpd: PHP Fatal error:  Call to undefined method MoodleQuickForm_hidden::MoodleQuickForm_hidden() in /opt/moodle/html/lib/pear/HTML/QuickForm/element.php on line 363


Logged


Latest Moodle requires a higher version of MySQL above SME’s, how did you install?


Logged

SME 8.0
Quad 6600
8gb DDR2 800
8 TB RAID 5
Dual Gigabit NIC
I Still Don’t KNOW WHAT I AM DOING. Please, don’t assume I know anything about Linux or Centos, I just know hardware


antdickens

There are a number of supported Moodle versions (that are supported by Moodle).
There is also the old sme server contrib.
You need to choose the correct version that matches the characteristics of your server operating system ie mysql & php versions for example, rather than just install the «latest» version.
Read the Moodle site for details.

What version did you install ?


Logged

Please search before asking, an answer may already exist.
The Search & other links to useful information are at top of Forum.


This is the Moodle server check page. I installed it as per the wiki.

Thanks

Environment
Check how your server suits current and future installation requirements

Moodle Version  1.9.2+ (Build: 20080910)

Server Checks
Name Information Report Status
moodle  version 1.0 is required and you are running 1.9.2 OK
unicode  must be installed and enabled OK
database mysql version 4.1.16 is required and you are running 5.1.69 OK
php  version 4.3.0 is required and you are running 5.3.3 OK
php_extension iconv should be installed and enabled for best results OK
php_extension mbstring should be installed and enabled for best results OK
php_extension curl should be installed and enabled for best results OK
php_extension openssl should be installed and enabled for best results OK
php_extension tokenizer should be installed and enabled for best results OK
php_extension xmlrpc should be installed and enabled for best results OK
php_extension ctype should be installed and enabled for best results OK
php_extension pcre must be installed and enabled OK


Logged


Well that’s a new spin. There is an error.
I will try to install per wiki into my VM. Won’t happen until tomorrow morning, though.
What other contribs, addons, modifications do you have done to your SME install? Was it an upgraded server or CD ISO install?
I know there is a version of Moodle 2.0 that runs, but everything here on Contribs.org should work as posted. So I will work on that first before revising any wiki instructions.


Logged

SME 8.0
Quad 6600
8gb DDR2 800
8 TB RAID 5
Dual Gigabit NIC
I Still Don’t KNOW WHAT I AM DOING. Please, don’t assume I know anything about Linux or Centos, I just know hardware


Moving to Contribs section of the Forums.


Logged


 moodle 196 — 198 is required to run on sme8 because of php5.3


Logged


Ошибка с кодом 500 выдается в том случае, когда причину сбоя нельзя отнести ни к какой другой категории ошибок (502, 503 и т. д.). По сути она означает «что-то произошло, а что — непонятно». В сообщении об ошибке 500, которое выдается на странице браузера, стандартно также нет сведений о ее причинах.

Как же без наличия информации определить и исправить ошибку? На практике чаще всего она вызывается сбоями в одном из основных компонентов сайта:

  • в правах доступа к файлам и каталогам;
  • в файле .htaccess;
  • в скриптах;
  • в CMS (движке сайта).

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

Для определения причины ошибки:

  • смотрим логи сервера — часто по ним можно понять, на каком этапе произошел сбой;
  • если логи не добавили ясности, или вы не можете их посмотреть — перебирайте все возможные варианты, начиная с тех, которые кажутся наиболее вероятными в вашем случае. Например, если вы не трогали перед возникновением ошибки файл .htaccess, но устанавливали новые плагины на сайт, начать нужно с проверки последнего.

500 Internal Server Error

Некорректные права доступа

Каждый каталог и файл на сервере имеет определенную трехзначную кодировку прав доступа к нему. Например, 777 — такой доступ означает, что любой сторонний пользователь может изменять этот файл или папку. Для обеспечения безопасности сервер блокирует файлы, которые имеют такие широкие права доступа. В результате страница сайта не отображается, так как сервер не отдает содержимое нужных файлов, и выдается ошибка 500.

Рекомендуется выставлять права не выше 750 — для папок, и 640 — для исполняемых файлов.

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

права доступа

Как определить, что ошибка 500 возникла именно из-за этого?

Во-первых, посмотрите, какой вид имеет ошибка на экране браузера. Если вы видите текст «Internal Server Error» — то, скорее всего, дело именно в .htaccess. В случаях сбоев в работе скриптов или CMS текст ошибки обычно выглядит как «HTTP ERROR 500».

Во-вторых, попробуйте добавить в конец наименования файла .htaccess любые символы. Например, переименуйте его в .htaccess2233. Сервер не будет использовать переименованный файл, и сайт будет запускаться без него. Перезагрузите страницу, на которой была ошибка. Если она исчезла — значит, причина в .htaccess.

Что может быть неверным в файле и как это исправить?

Самый простой способ устранить ошибку 500 из-за .htaccess — отменить последние изменения в нем или загрузить файл из бекапа. Если это невозможно или нежелательно, проверьте эти варианты:

  • наличие невидимых неразрывных пробелов (BOM). Если вы изменяли файл, используя не совсем подходящий редактор или кодировку, в него могли быть добавлены такие символы. Пересохраните файл в кодировке UTF-8 и загрузите на сервер;
  • знак # не в начале строки. Этот знак ставится перед началом комментария. Некоторые пытаются добавить комментарий в .htaccess в конце строки, но последние версии Apache не поддерживают такой синтаксис, и в результате вы видите ошибку 500. Для комментария нужно выделять целую строку;
  • некорректные директивы Options. В зависимости от версии серверного ПО, можно их либо полностью закомментировать, либо попробовать исправить Options All -Indexes на директиву Options -Indexes, а Options +FollowSymLinks на директиву Options +SymLinksIfOwnerMatch;
  • некорректные директивы +ExecCGI, IfVersion, AddHandler, php_value, php_flag, MultiViews. Если в вашем файле встречаются такие, попробуйте поочередно их удалить (или закомментировать), проверяя, исчезла ли ошибка.

Сбои в скриптах

Ошибка 500 здесь может вызываться двумя основными причинами:

  • Неверный синтаксис или права доступа скрипта.
  • Слишком долгое выполнение скрипта.

В первом случае:

  • включите отображение ошибок в настройках сервера (или обратитесь к техподдержке, они помогут это сделать). Тогда при перезагрузке страницы вы увидите надпись, в которой будет имя файла и конкретная строка в нем, вызывающая ошибку;
  • проверьте, правильно ли вы загружали файлы скриптов через FTP , а лучше перезагрузите их правильным образом — в режиме ASCII. Хотя для некоторых FTP-клиентов, например, для FileZilla, лучше включать двоичный режим передачи: так содержимое файлов будет передано корректно и без искажений;
  • проверьте права доступа к файлу скриптов — они должны быть выставлены на уровне 750 или 755.

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

Ошибки в CMS

Ошибки в CMS

  • Довольно часто ошибка 500 возникает после установки плагинов и дополнений к CMS<. Особенно это актуально на WordPress. Сайт на этом движке, как конструктор, собирается из базы и десятков различных плагинов. При этом плагины могут конфликтовать между собой. Решение простое — отключите дополнения, которые вы недавно устанавливали, и посмотрите, исчезнет ли ошибка. Если да — дело в плагине и лучше поставить другой.
  • Устаревшая версия PHP. Она может конфликтовать с новыми скриптами или плагинами. Для обновления версии обратитесь к специалисту.
  • Обновление версии движка. Такие работы также лучше проводить при поддержке специалистов, которые комплексно проверят совместимость скриптов и дополнений с новой версией. Иначе можем получить конфликт и ошибку 500.

В статье мы расскажем, как исправить ошибку (код состояния) 500 со стороны пользователя и администратора сайта, а также подробно разберём, что такое ошибка запроса 500.

Что такое внутренняя ошибка сервера 500

Код ошибки 5хх говорит о том, что браузер отправил запрос корректно, но сервер не смог его обработать. Что значит ошибка 500? Это проблема сервера, причину которой он не может распознать.

Сообщение об ошибке сопровождается описанием. Самые популярные варианты:

  • Внутренняя ошибка сервера 500,
  • Ошибка 500 Internal Server Error,
  • Временная ошибка (500),
  • Внутренняя ошибка сервера,
  • 500 ошибка сервера,
  • Внутренняя ошибка HTTP 500,
  • Произошла непредвиденная ошибка,
  • Ошибка 500,
  • HTTP status 500 internal server error (перевод ― HTTP статус 500 внутренняя ошибка сервера).

Дизайн и описание ошибки 500 может быть любым, так как каждый владелец сайта может создать свою версию страницы. Например, так выглядит страница с ошибкой на REG.RU:

Как ошибка 500 влияет на SEO-продвижение

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

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

Проверить, осталась ли страница на прежних позициях, можно с помощью Google Search Console. Если робот исключил страницу из поисковой выдачи, её можно добавить снова.

Код ошибки 500: причины

Если сервер вернул ошибку 500, это могло случиться из-за настроек на web-хостинге или проблем с кодом сайта. Самые распространённые причины:

  • ошибки в файле .htaccess,
  • неподходящая версия PHP,
  • некорректные права на файлы и каталоги,
  • большое количество запущенных процессов,
  • большие скрипты,
  • несовместимые или устаревшие плагины.

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

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

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

Перезагрузите страницу

Удаленный сервер возвращает ошибку не только из-за серьёзных проблем на сервере. Иногда 500 ошибка сервера может быть вызвана небольшими перегрузками сайта.

Чтобы устранить ошибку, перезагрузите страницу с помощью сочетания клавиш:

  • на ПК — F5,
  • на ноутбуке — Fn + F5,
  • на устройствах от Apple — Cmd + R.

Обратите внимание! Если вы приобретаете товары в интернет-магазине и при оформлении заказа появляется 500 Internal Server Error (перевод — внутренняя ошибка сервера), при перезагрузке страницы может создаться несколько заказов. Поэтому сначала проверьте, оформился ли ваш предыдущий заказ. Если нет, попробуйте оформить заказ заново.

Очистите кэш и cookies браузера

Кэш и cookies сохраняют данные посещаемых сайтов и данные аутентификаций, чтобы в будущем загружать веб-ресурсы быстрее. Если на ресурсе уже был статус ошибки 500, при повторном входе на сайт может загружаться старая версия страницы с ошибкой из кэша, хотя на самом деле страница уже работает. Очистить кэш и куки браузера вам поможет инструкция.

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

Что делать, если вы владелец сайта

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

Ниже рассмотрим самые популярные причины и способы решения.

Ошибки в файле .htaccess

Неверные правила в файле .htaccess — частая причина возникновения ошибки. Чтобы это проверить, найдите .htaccess в файлах сайта и переименуйте его (например, в test). Так директивы, прописанные в файле, не повлияют на работу сервера. Если сайт заработал, переименуйте файл обратно в .htaccess и найдите ошибку в директивах. Если вы самостоятельно вносили изменения в .htaccess, закомментируйте новые строки и проверьте доступность сайта.Также может помочь замена текущего файла .htaccess на стандартный в зависимости от CMS.

Найти директиву с ошибкой можно с помощью онлайн-тестировщика. Введите содержимое .htaccess и ссылку на сайт, начиная с https://. Затем нажмите Test:


Произошла непредвиденная ошибка

На экране появится отчёт. Если в .htaccess есть ошибки, они будут выделены красным цветом:


500 ошибка nginx

Активирована устаревшая версия PHP

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

Установлены некорректные права на файлы и каталоги сайта

В большинстве случаев корректными правами для каталогов являются «755», для файлов — «644». Проверьте, правильно ли они установлены, и при необходимости измените права на файлы и папки.

Запущено максимальное количество процессов

На тарифах виртуального хостинга REG.RU установлены ограничения на количество одновременно запущенных процессов. Например, на тарифах линейки «Эконом» установлено ограничение в 18 одновременно запущенных процессов, на тарифах «+Мощность» ― 48 процессов. Если лимит превышен, новый процесс не запускается и возникает системная ошибка 500.

Такое большое число одновременных процессов может складываться из CRON-заданий, частых подключений с помощью почтовых клиентов по протоколу IMAP, подключения по FTP или других процессов.

Чтобы проверить количество процессов, подключитесь по SSH. Выполните команду:

ps aux | grep [u]1234567 |wc -l

Вместо u1234567 укажите ваш логин хостинга: Как узнать логин хостинга.

Чтобы посмотреть, какие процессы запущены, введите команду:

Вместо u1234567 укажите логин услуги хостинга.

Командная строка отобразит запущенные процессы:


Код ошибки 500

Где:

  • u1234567 — логин услуги хостинга,
  • 40522 — PID процесса,
  • S — приоритет процесса,
  • /usr/libexec/sftp-server — название процесса.

Процесс можно завершить командой kill, например:

Вместо 40522 укажите PID процесса.

Чтобы решить проблему, вы также можете:

  • увеличить интервал запуска заданий CRON,
  • ограничить количество IMAP-соединений в настройках почтового клиента. Подробнее в статье Ограничение IMAP-соединений,
  • проанализировать запущенные процессы самостоятельно или обратившись за помощью к разработчикам сайта.

Если вам не удалось самостоятельно устранить ошибку 500, обратитесь в техподдержку.

Скрипты работают слишком медленно

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

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

Ошибка 500 на сайте, созданном на WordPress

WordPress предлагает много плагинов для создания хорошего сайта. Они значительно расширяют возможности CMS. Однако они же могут нарушать работу сайта и вызывать ошибку 500. Вызвать ошибку могут как недавно установленные плагины, так и старые.

Для начала проверьте, нужно ли обновить плагины. Часто устаревшие плагины перестают работать и вызывают проблемы работы сайта. Если все плагины обновлены, но 500 Internal Server Error остаётся, отключите все плагины, чтобы убедиться, что именно они мешают работе сайта. Как только станет понятно, что виноват один из плагинов, отключайте их по очереди, пока не найдёте тот, который нарушает работу сервера.


Как отключить плагин в WordPress

  1. 1.

  2. 2.

    Перейдите во вкладку «Плагины» ― «Установленные».

  3. 3.

    Нажмите Деактивировать у плагина, который, как вам кажется, повлиял на работу сайта:

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

Понравилась статья? Поделить с друзьями:
  • Monster hunter world ошибка 50086 mw1
  • Monster hunter world код ошибки 400 mw1
  • Monster hunter world как изменить внешность брони
  • Monster hunter world err12 graphics device crashed как исправить
  • Monster hunter rise неустранимая ошибка приложения