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
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 file, but the error doesn’t show up there so debugging this has been a pain in the ass.
How do I cause Apache to log Internal 500 errors into the error log?
asked Jan 19, 2011 at 3:04
2
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:
-
Locate your php.ini file:
el@apollo:~$ locate php.ini /etc/php5/apache2/php.ini
-
Edit that file as root:
sudo vi /etc/php5/apache2/php.ini
-
Find this line in php.ini:
display_errors = Off
-
Change the above line to this:
display_errors = On
-
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
-
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.
-
Restarting PHP and Apache should apply the change.
-
Do what you did to cause the 500 Internal Server error again, and check the log:
tail -f /var/log/apache2/error.log
-
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
answered Dec 11, 2013 at 6:20
Eric LeschinskiEric Leschinski
147k96 gold badges418 silver badges335 bronze badges
9
I just ran into this and it was due to a mod_authnz_ldap misconfiguration in my .htaccess file. Absolutely nothing was being logged, but I kept getting a 500 error.
If you run into this particular issue, you can change the log level of mod_authnz_ldap like so:
LogLevel warn authnz_ldap_module:debug
That will use a log level of debug for mod_authnz_ldap but warn for everything else (https://httpd.apache.org/docs/2.4/en/mod/core.html#loglevel).
answered May 13, 2013 at 20:55
bmaupinbmaupin
14.5k5 gold badges89 silver badges94 bronze badges
3
Check your php error log which might be a separate file from your apache error log.
Find it by going to phpinfo()
and check for error_log attribute.
If it is not set. Set it: https://stackoverflow.com/a/12835262/445131
Maybe your post_max_size is too small for what you’re trying to post, or one of the other max memory settings is too low.
answered Jul 18, 2012 at 16:50
jsonHjsonH
1671 silver badge5 bronze badges
1
If your Internal Server Error information doesn’t show up in log files, you probably need to restart the Apache service.
I’ve found that Apache 2.4 (at least on Windows platform) tends to stubbornly refuse to flush log files—instead, logged data remains in memory for quite a while. It’s a good idea from the performance point of view but it can be confusing when developing.
answered Aug 22, 2015 at 19:17
Álvaro GonzálezÁlvaro González
142k41 gold badges262 silver badges360 bronze badges
2
Please Note: The original poster was not specifically asking about PHP. All the php centric answers make large assumptions not relevant to the actual question.
The default error log as opposed to the scripts error logs usually has the (more) specific error. often it will be permissions denied or even an interpreter that can’t be found.
This means the fault almost always lies with your script. e.g you uploaded a perl script but didnt give it execute permissions? or perhaps it was corrupted in a linux environment if you write the script in windows and then upload it to the server without the line endings being converted you will get this error.
in perl if you forget
print "content-type: text/html\r\n\r\n";
you will get this error
There are many reasons for it. so please first check your error log and then provide some more information.
The default error log is often in /var/log/httpd/error_log
or /var/log/apache2/error.log
.
The reason you look at the default error logs (as indicated above) is because errors don’t always get posted into the custom error log as defined in the virtual host.
Assumes linux and not necessarily perl
answered Jan 19, 2011 at 4:13
DeveloperChrisDeveloperChris
3,4222 gold badges24 silver badges39 bronze badges
7
The answers by @eric-leschinski is correct.
But there is another case if your Server API is FPM/FastCGI (Default on Centos 8 or you can check use phpinfo() function)
In this case:
- Run
phpinfo()
in a php file; - Looking for
Loaded Configuration File
param to see where is config file for your PHP. - Edit config file like @eric-leschinski ‘s answer.
-
Check
Server API
param.
If your server only use apache handle API -> restart apache.
If your server use php-fpm you must restart php-fpm servicesystemctl restart php-fpm
Check the log file in php-fpm log folder. eg
/var/log/php-fpm/www-error.log
answered Dec 28, 2019 at 4:01
Ngô Văn ThaoNgô Văn Thao
3,6911 gold badge20 silver badges24 bronze badges
Please check if you are disable error reporting somewhere in your code.
There was a place in my code where I have disabled it, so I added the debug code after it:
require_once("inc/req.php"); <-- Error reporting is disabled here
// overwrite it
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
answered Jun 29, 2020 at 15:24
BlackBlack
18.2k39 gold badges158 silver badges273 bronze badges
Add HttpProtocolOptions Unsafe
to your apache config file and restart the apache server. It shows the error details.
answered Mar 16, 2019 at 19:16
SaberSaber
2,4601 gold badge25 silver badges40 bronze badges
In my case it was the ErrorLog directive in httpd.conf. Just accidently noticed it already after I gave up. Decided to share the discovery )
Now I know where to find the 500-errors.
answered Feb 16, 2018 at 5:40
2
Check that the version of php you’re running matches your codebase. For example, your local environment may be running php 5.4 (and things run fine) and maybe you’re testing your code on a new machine that has php 5.3 installed. If you are using 5.4 syntax such as [] for array() then you’ll get the situation you described above.
answered Apr 9, 2013 at 19:31
John ErckJohn Erck
9,4788 gold badges61 silver badges71 bronze badges
1
Try accessing a static file. If this is not working either then
go to all directories from the root «/» or «c:\» to the directory of your file and check if they contain «.htaccess» files.
I once left a file in «c:\» and it had the most strange results.
answered May 28, 2016 at 4:05
LotharLothar
12.6k6 gold badges72 silver badges121 bronze badges
1
This misconfiguration message happened for me when I used the # comment symbol in other than column 1 (remember, Apache is old software where column numbers and whitespace can sometimes be significant).
Options -Indexes # Never show folder indices
answered Aug 19 at 17:33
В данной статье мы рассмотрим наиболее вероятные причины возникновения ошибки 500 “Internal Server Error”.
Причины указаны в порядке вероятности возникновения.
-
Использование в файлах
.htaccess
недопустимых на нашем хостинге конструкций, напримерOptions
или
-MultiViewsphp_value
иphp_flag
. Вы можете открыть файл.htaccess
текстовым редактором и
найти строки, в начале которых используются указанные конструкции. Найденные строки можно удалить
или добавить#
в начале. Файл.htaccess
может находиться в корневом каталоге вашего сайта — на
том же уровне, что и файлы index.php или index.html или robots.txt. -
Скрипт пытается получить больше памяти, чем ограничено параметром
memory_limit
. Обычно
достаточно увеличить этот параметр в панели
управления. Увеличивать стоит постепенно, с шагом в
16 — 32 Мб, пока ошибка не пропадет. Новые настройки PHP вступают в силу в течение 3-5 минут. -
В панели управления или в
php.ini
включены не совместимые друг с другом расширения php.
Например, одновременное включение eaccelerator и APC, либо eaccelerator и XCache почти наверняка
будет приводить к ошибке Segmentation Fault и, как следствие, к ошибке Internal Server Error на
сайте. -
Если вы редактировали какие либо файлы сайта в ОС Windows, то при сохранении в файл могли
добавиться не совместимые с unix-форматом символы переноса строки. Для корректной работы необходимо
использовать совместимые с unix-форматом переносы строк. Например, в
Notepad++ этот параметр можно настроить в меню “Правка” -> “Формат
конца строк” -> “Преобразовать в UNIX-формат”. -
Слишком долгая работа скрипта (может быть связано, например, с выгрузкой товаров на сайте, либо
другими долгими запросами). Если веб-сервер не получает никакого ответа от скрипта в течение 120
секунд, скрипт считается зависшим и его работа принудительно завершается с выдачей ошибки 500.
Изменить это ограничение в индивидуальном порядке на виртуальном хостинге нельзя. В качестве решения
вы можете запускать выполнение скрипта, разбив данные на части, либо через
cron либо напрямую через
ssh-соединение. -
Скрипт возвращает 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-консолью.
Для этого перейдите на страницу Вашего сайта.
Выберите вкладку “Файлы” и нажмите на ней кнопку “Терминал”.
В открывшемся окне введите команду.
cd log
Для того чтобы посмотреть список всех доступных лог файлов введите команду.
ls -la
Чтобы вывести информация из файла введите команду.
cat error.log
Просмотр логов ошибок c помощью файлового менеджера
Для того чтобы посмотреть логи ошибок можно воспользоваться файловым менеджером.
Для этого перейдите на страницу Вашего сайта.
Выберите вкладку “Файлы” и нажмите на ней кнопку “Файловый менеджер”.
Нажмите два раза на папку log, для того чтобы она открылась.
Для прочтения любого файла два раза нажмите на нужный файл.
Инструкция для Виртуального хостинга
Включение лога ошибок apache
Однозначно определить источник ошибки поможет включение лога ошибок. Для этого потребуется зайти в
панель управления , слева от названия сайта кликнуть на
иконку с тремя горизонтальными полосками и выбрать “Журнал ошибок”. Когда ошибки возникнут, то в
домашнем каталоге на сервере появится файл вида sitename.ru-error.log, где sitename.ru — имя сайта,
для которого вы включили лог ошибок.
Логи ошибок сохраняются в обычные текстовые файлы, их можно просмотреть подключившись к хостингу по
протоколу FTP. Инструкция по подключению.
Так же может быть полезно включить лог php ошибок поставив
галочку напротив пункта error.log и нажав кнопку сохранить. Лог ошибок будет сохранен в файле
log/php-errors.log.
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.
- more /var/log/httpd/error_log | grep [file name]
- 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.
- tail -f /var/log/httpd/error_log
- 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.
- tail -20 /var/log/httpd/error_log
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
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
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»;