При разработке веб-сайтов и веб-приложений можно столкнуться с ошибкой 500 internal server error. Сначала она может испугать и ввести в заблуждение, поскольку обычно веб-сервер выдает более конкретные ошибки, в которых указана точная причина проблемы, например, превышено время ожидания, неверный запрос или файл не найден, а тут просто сказано что, обнаружена внутренняя ошибка.
Но не все так страшно и в большинстве случаев проблема вполне решаема и очень быстро. В этой статье мы разберем как исправить ошибку 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:
vi /etc/php/7.2/php.ini
display_errors = On
Перезапустите php-fpm:
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. Настройте его правильно или отключите:
setenforce 0
Выводы
В этой статье мы разобрали что делать если на вашем сайте встретилась ошибка 500 internal server error nginx. Как видите проблема вполне решаема и в большинстве случаев вам помогут действия описанные в статье. А если не помогут, напишите свое решение в комментариях!
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
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
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
2
You display_errors
directive is set to no
.
To fix this:
-
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
-
Restart your apache with:
sudo systemctl restart apache2
-
To have the same behaviour on the
cli
edit the/etc/php/7.0/cli/php.ini
-
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:
-
step 1
will change themaster value
, and -
step 4
will change thelocal value
.
answered Feb 8, 2017 at 19:25
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
76.8k6 gold badges107 silver badges166 bronze badges
answered Sep 10, 2018 at 5:37
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
1
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
- Печать
Страницы: [1] Вниз
Тема: пытаюсь открыть в браузере index.php, получаю (HTTP 500 Internal Server Error) (Прочитано 11925 раз)
0 Пользователей и 1 Гость просматривают эту тему.
![Оффлайн](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
neohackс
Вот лог ошибок апача:
Конфиг apache2.conf
Конфиг сайта:
Проблема в том что когда пытаюсь открыть в браузере index.php, получаю (HTTP 500 Internal Server Error)
« Последнее редактирование: 01 Февраля 2012, 23:52:52 от Дмитрий Бо »
![Оффлайн](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
victor00000
![Оффлайн](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
neohackс
Такого каталога вообще нет. Кстати я пробил, 66.249.72.122 — гугловский поисковый IP. Интересно зачем он лезет в отчеты сквида))
А другой IP, 95.28.52.9 — мой
![Оффлайн](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
victor00000
grep -Rs "/var/www/work" /etc
![Оффлайн](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
drako
sudo chown -R www-data:www-data /var/www/ решит вашу проблему.
![Оффлайн](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
neohackс
Попробую сейчас. Отпишу о результатах.
——————————————
Вот, теперь браузер выдает мне такое сообщение:
Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0
Fatal error: Unknown: Failed opening required ‘/var/www/index.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in Unknown on line 0
Причем каталогов :/usr/share/php и :/usr/share/pear нет на сервере вообще.
Есть :/usr/share/php5
« Последнее редактирование: 02 Февраля 2012, 10:47:53 от neohackс »
![Оффлайн](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
unimix
Наверно проблемы с правами файлов в /var/www. Попробуй следующее:
sudo chmod -R +r /var/www
Хотя где ошибка (in Unknown on line 0) не понятно.
« Последнее редактирование: 02 Февраля 2012, 11:32:22 от unimix »
![Оффлайн](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
neohackс
Спасибо. Проблема действительно была в правах на файлы.
- Печать
Страницы: [1] Вверх
Before starting, I’d like to ssay this is my first experience with VPS
, I have an Ubuntu 18.04 64bit minimal server.
For everything I tried so far I didn’t tried using complex application. Just plain html file with
Hello
message and WordPress blank installation.
To begin with, I’m installing Vesta Panel
because it’s easier for me to control some basic tasks and configurations. In order to install this panel, I’m using nginx + php-ftpm
. After I install WordPress with this configuration I’m getting 500 error with this message:
2020/06/23 23:09:09 [error] 12335#12335: *11 connect() failed (111: Connection refused) while connecting to upstream, client: x.x.x.x, server: example.com, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9001", host: "example.com"
This error only appears when I try to access the WordPress index page, or any file with the naem index.php
, if it’s an index.html
file it loads properly.
After that I restored the VPS
and installed Vesta Panel
using nginx + apache
. With this configuration, WordPress is working as expected. When I access my domain example.com
the steps to create an WordPress website appears as expected.
With both configurations, the folder holding all the websites files is /home/admin/web/{domain.com}/public_html
.
Edit: As requested in the comments, I’m adding more information to the question.
systemctl status php-fpm.service
returns:
php-fpm.service - LSB: starts php7.2-fpm
Loaded: loaded (/etc/init.d/php-fpm; generated)
Active: active (exited) since Wed 2020-06-24 01:44:40 UTC; 10h ago
Docs: man:systemd-sysv-generator(8)
Tasks: 0 (limit: 614)
CGroup: /system.slice/php-fpm.service
Jun 24 01:44:40 agdevision.com.br systemd[1]: Starting LSB: starts php7.2-fpm...
Jun 24 01:44:40 agdevision.com.br systemd[1]: Started LSB: starts php7.2-fpm.
sudo journalctl -u php-fpm.service
returns:
-- Logs begin at Fri 2019-03-08 08:44:31 UTC, end at Wed 2020-06-24 12:08:35 UTC. --
Jun 24 01:44:40 agdevision.com.br systemd[1]: Starting LSB: starts php7.2-fpm...
Jun 24 01:44:40 agdevision.com.br systemd[1]: Started LSB: starts php7.2-fpm.