При разработке веб-сайтов и веб-приложений можно столкнуться с ошибкой 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. Как видите проблема вполне решаема и в большинстве случаев вам помогут действия описанные в статье. А если не помогут, напишите свое решение в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Sometimes NGINX server may give 500 Internal Server Error due to various reasons. In this article we will look at what does 500 Internal Server Error mean in NGINX and how to fix 500 Internal Server Error in NGINX.
NGINX gives 500 Internal Server Error when there is a server-side error that prevents NGINX from returning a proper response. It can be due to many different reasons such as faulty script, missing files referenced by code, inadequate file permissions, etc. NGINX is typically used as a reverse proxy server, so the most common reason for 500 Internal server is an error in one of its web servers like Apache that has encountered an issue and returned a 500 error response to NGINX, which is then returned to client browsers. There are various ways to fix internal server error in NGINX.
Bonus Read : How To Fix 504 Gateway Timeout Error in NGINX
How to Fix 500 Internal Server Error in NGINX
Here are the steps to fix 500 Internal Server Error in NGINX on localhost, CPanel, PHP, Ubuntu and other platforms.
1. Hard Refresh
Sometimes you may get 500 internal server error in NGINX because your server is being restarted at that moment, or there are too many requests for web server to handle.
So it doesn’t have enough resources to serve your request.
In such cases, you can simply do a hard refresh of your page to force the browser to get latest web page version and fix 500 internal server error in NGINX. You can do this by pressing
- Windows: Ctrl + F5
- Mac: Apple + R or Cmd + R
- Linux: F5
Bonus Read : How to Fix 502 Bad Gateway Error in NGINX
2. Examine Server Logs
Open your server log in a text editor to analyze the most recent requests. Every server log contains information about requested URLs and response code for each request.
Find out which requests result in 500 internal server error. It may be that only one page, or a few pages give this error while others work fine.
Find out which requests cause 500 internal server error. Once you have identified the problematic URLs, open a browser and request them again to confirm that is indeed the case.
Bonus Read : How to Increase Request Timeout in NGINX
3. Examine Your Script
Next, analyze the script to process the problematic requests. Is it actually present at the right location? Are you referencing it properly, in your URL mapping/routing file?
If your script refers to another file, find out if that file path is correct. If you have referenced any program/function, have you called it correctly?
4. Check File/Folder Permission
This can also be due to improper file/folder permissions. Did you add/modify any file/folder recently?
Typically, files need a 644 permission and folders need a 755 permission. You can use FileZilla (Windows) and Chmod (Linux) to modify file permissions.
You can also look at the permissions of other files & folders in your code and update the same for your files/folders accordingly.
Bonus Read : How to Increase File Upload Size in NGINX
5. Check redirections
If you have incorrectly setup any redirections in web server, it can give 500 internal server error. For example, if you use Apache web server, make sure you have properly configured mod_rewrite module and .htaccess file.
Also use a third-party tool to check the syntax of redirection/URL rewrite rules in your server configuration file.
6. Increase Script Timeout
You may also get 500 internal server error in NGINX if your web server (e.g Apache) is timing out on the request. In such cases, increase your web server (not NGINX) timeout value so that it stays connected to NGINX longer, and returns a proper response.
Hopefully, the above tips will help you fix 500 internal server error in NGINX.
Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!
Related posts:
- About Author
If you’ve ever encountered the 500 internal server error Nginx on your website, we know how frustrating and stressful it can be. You may have spent hours or even days creating and designing your website, and the thought of visitors being unable to access it can be disheartening.
But you do not need to worry, we’re here to help you to fix this Nginx server error with the best possible troubleshooting methods!
In this Guide, we’ll walk you through the main causes that trigger 500 internal server error Nginx, How to prevent it, and the steps to fix the Nginx 500 error and get your website back up and running.