Ubuntu server 500 internal server error

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

При разработке веб-сайтов и веб-приложений можно столкнуться с ошибкой 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 License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

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

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
    

I’m running ubuntu 12.04

I’m getting a huge number of «500 Internal Server Error» errors whenever I try to apt-get install/upgrade. aptitude yields exactly the same errors. I know there are supposed to be «zillions» of threads about this on the web but none of them seem to work for me. Most of them seem to be related to installing a specific package, but I get the errors whenever I use apt-get or aptitude

I know this is supposed to be a generic error, but there’s nothing in the /var/log/apt folder that provides any information, or even acknowledges the error. (The only two files in there are term.log and history.log).

As some have recommended, I’ve modified my /etc/apt/sources.list file so that the top three lines are

deb http://us-west-1.ec2.archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse
deb http://us-west-1.ec2.archive.ubuntu.com/ubuntu/ precise-updates main restricted universe multiverse
deb http://us-west-1.ec2.archive.ubuntu.com/ubuntu/ precise-security main restricted universe multiverse

But these are giving errors as well.

Can anybody please advise based on this information, or suggest how I can get a more informative error description?

Thanks for help in advance

Here are just a few of errors I get from apt-get upgrade

Err http://archive.canonical.com precise/partner amd64 Packages 500  Internal Server Error
Err http://archive.canonical.com precise/partner i386 Packages 500  Internal Server Error
Err http://archive.canonical.com precise/partner Sources 500  Internal Server Error
Err http://dl.google.com stable/main amd64 Packages 500  Internal Server Error
Err http://dl.google.com stable/main i386 Packages 500  Internal Server Error
Err http://extras.ubuntu.com precise/main amd64 Packages 500  Internal Server Error
Err http://extras.ubuntu.com precise/main i386 Packages 500  Internal Server Error
Err http://extras.ubuntu.com precise/main Sources 500  Internal Server Error
Err http://ppa.launchpad.net precise/main amd64 Packages 500  Internal Server Error
Err http://ppa.launchpad.net precise/main i386 Packages 500  Internal Server Error
Err http://ppa.launchpad.net precise/main Sources 500  Internal Server Error
Err http://security.ubuntu.com precise-security/main amd64 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/main i386 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/main Sources 500  Internal Server Error
Err http://security.ubuntu.com precise-security/multiverse amd64 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/multiverse i386 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/multiverse Sources 500  Internal Server Error
Err http://security.ubuntu.com precise-security/restricted amd64 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/restricted i386 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/restricted Sources 500  Internal Server Error
...
Err http://us-west-1.ec2.archive.ubuntu.com precise/main amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise/main i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise/multiverse amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise/multiverse i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise/restricted amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise/restricted i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/main amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/main i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/multiverse amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/multiverse i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/restricted amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/restricted i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/universe amd64 Packages 500  Internal Server Error

~
~

Одна из наиболее распространенных ошибок, возникающих при просмотре веб-страниц, — это «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, означающий, что что-то пошло не так с веб-сервером, на котором размещен сайт, который вы посещаете.

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

One of the most common errors that occur when browsing the web is the “500 Internal Server Error”. This message indicates that the webserver is experiencing technical problems.

This article explains what a 500 error means, why you’re getting an HTTP 500 code, and how to troubleshoot these errors.

What is a 500 Internal Server Error #

Each time you open a web page, your browser sends a request to the server hosting the site, which returns the requested data and response code. The HTTP response status codes indicate whether the request has been successful or not.

Responses are categorized in five classes. The codes in the 500 to 599 range are indicating a server error.

The HTTP status code 500 is a generic error response that is returned by the server when no other error code is appropriate. It can be caused by a number of problems that prevent the server from completing the request.

If the page you are visiting throws 500 Error there is nothing much you can do since the error is not caused by your browser or Internet connection. Even though the error is on the server-side, you can try some of the following options:

  • Reload your browser or try with another one. The chances that the page will load when you refresh your browser are low, but still, it’s worth giving it a try.
  • Try to clear your browser cache. If the page that shows 500 error is cached, after the cache is cleared, the browser will request a new version of the page.
  • Come back later. The webmaster may fix the server issue in the meantime.
  • Contact the website owners. The last remaining option is to get in touch with the person responsible for maintaining the website.

Troubleshooting 500 Error #

  • A permission issue. When the webserver has no permissions to access the site files, it may throw an HTTP 500 error. The solution to this issue is to change the website file’s permissions recursively .
  • .htaccess syntax error. If you are using Apache as a webserver, then most probably you have a .htaccess file in your site root directory. Invalid syntax or non-existing module directive can lead to a 500 error.
  • Database related issue. HTTP Error 500 can also be caused by incorrect database server information or a corrupted database.
  • Issues with plugins and themes. If you are running WordPress or similar CMS, the 500 error can appear after updating or modifying a plugin/theme.
  • Server issues. A corrupted filesystem or exhausted memory can lead to 500 error.
  • Node.js modules. If you have Node.js based site, updating modules can cause a 500 internal server error.
  • Hacked site. Quite often a malicious code that is injected into your website results with a 500 error.
  • Incompatible module. Loading an incompatible PHP or Apache module throws the 500 error.
  • External Resource Timeout. If the server communicates with external service and if those services are not reachable the server will show a 500 error message.

The best way to determine why the 500 error occurred is to check the server log files. The location od the log files depends on your Linux distribution and the web server. The most common locations for Apache and Nginx are as follows:

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

If your application is built on Node.js, check the Node.js logs.

Typically the server log contain a detailed information about the error that will help you to identify and fix the error.

Conclusion #

The 500 Internal Server Error is a general HTTP status code meaning that something went wrong with the web server hosting the site you’re visiting.

If you have any questions or feedback, feel free to leave a comment.

Понравилась статья? Поделить с друзьями:
  • Ubuntu repository gpg error
  • Ubuntu read only file system как исправить
  • Ubuntu phpmyadmin error 1045
  • Ubuntu permission denied как исправить
  • Ubuntu network is unreachable как исправить