Ubuntu apache internal server error

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 ...

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
    

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

Содержание

  1. Что такое внутренняя ошибка сервера 500
  2. Что такое ошибка HTTP 500
  3. Устранение неполадок 500 Ошибка
  4. Выводы
  5. How to Fix 500 Internal Server Error in Apache
  6. What is 500 Internal Server Error in Apache
  7. How to Fix 500 Internal Server Error in Apache
  8. 1. Hard Refresh the Page
  9. 2. Examine Server Logs
  10. 3. Examine your script
  11. 4. Check File/Folder Permissions
  12. 5. Check .htaccess file
  13. 6. Increase Script Timeout
  14. ИТ База знаний
  15. Полезно
  16. Навигация
  17. Серверные решения
  18. Телефония
  19. Корпоративные сети
  20. Что такое ошибка 500 Internal Server Error?
  21. Windows Server
  22. Что такое ошибка HTTP 500
  23. Устранение ошибки HTTP 500
  24. 10 uncommon causes for Apache CGI Internal Server Error, and how to fix them
  25. Uncommon causes for Apache CGI Internal Server Error
  26. 1. Missing modules
  27. 2. Network timeouts (of API calls, remote scripts, etc.)
  28. 3. Old program (compiler) paths
  29. 4. Errors in application code
  30. 5. Old config files with wrong module paths
  31. 6. Security restrictions (Web application firewall, SELinux, etc.)
  32. 7. No Exec (no execution) restriction on the partition
  33. 8. Apache & .htaccess misconfiguration (no ExecCGI, no AllowOverride, etc.)
  34. 9. Wrong permissions on home directory
  35. 10. Chroot related errors that breaks file path
  36. Conclusion
  37. PREVENT YOUR SERVER FROM CRASHING!
  38. 2 Comments

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

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

Если ваше приложение построено на Node.js, проверьте журналы Node.js.

Обычно журнал сервера содержит подробную информацию об ошибке, которая поможет вам определить и исправить ошибку.

Выводы

Ошибка 500 Internal Server Error — это общий код состояния HTTP, означающий, что что-то пошло не так с веб-сервером, на котором размещен сайт, который вы посещаете.

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

Источник

How to Fix 500 Internal Server Error in Apache

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.

What is 500 Internal Server Error in Apache

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.

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

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 ?

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.

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.

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!

Источник

ИТ База знаний

Курс по Asterisk

Полезно

— Узнать IP — адрес компьютера в интернете

— Онлайн генератор устойчивых паролей

— Онлайн калькулятор подсетей

— Калькулятор инсталляции IP — АТС Asterisk

— Руководство администратора FreePBX на русском языке

— Руководство администратора Cisco UCM/CME на русском языке

— Руководство администратора по Linux/Unix

Навигация

Серверные решения

Телефония

FreePBX и Asterisk

Настройка программных телефонов

Корпоративные сети

Протоколы и стандарты

Что такое ошибка 500 Internal Server Error?

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

Одна из наиболее распространенных ошибок, возникающих при просмотре веб-страниц, — это ошибка 500 Internal Server Error. Это сообщение указывает на то, что на веб-сервере возникли технические проблемы.

Windows Server

Все самое главное про внедрение, управление и поддержку инфраструктуры MS Windows Server

Рассказываем означает ошибка 500, почему вы получаете код HTTP 500 и как устранить эти ошибки.

Что такое ошибка HTTP 500

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

Ответы делятся на пять классов. Коды в диапазоне от 500 до 599 указывают на ошибку сервера.

Код состояния HTTP 500 — это общий ответ об ошибке, который возвращается сервером, когда другой код ошибки не подходит. Это может быть вызвано рядом проблем, которые не позволяют серверу выполнить запрос.

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

  • Перезагрузите браузер или попробуйте использовать другой. Шансы на то, что страница загрузится при обновлении браузера, невелики, но все же стоит попробовать.
  • Попробуйте очистить кеш браузера. Если страница, на которой отображается ошибка 500, кэшируется, после очистки кеша браузер запросит новую версию страницы.
  • Вернуться позже. Тем временем веб-мастер может исправить проблему с сервером.
  • Свяжитесь с владельцами сайтов. Последний оставшийся вариант — связаться с лицом, ответственным за обслуживание веб-сайта.

Устранение ошибки HTTP 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 следующие:

Если ваше приложение построено на Node.js, проверьте логи Node.js.

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

Источник

10 uncommon causes for Apache CGI Internal Server Error, and how to fix them

by Visakh S | Sep 19, 2018

Apache’s CGI mode allows webmaster’s to reduce memory usage. It is the preferred way to run many low traffic websites.

But the CGI mode is pretty sensitive to things such as permissions and file encoding, that leads to 500 Internal Server Error.

In our role as Support Engineers for web hosts, we’ve seen a wide range of causes for this error.

Some common causes and their fixes are:

  • Wrong file or folder permissions – Script files and directories must have EXACTLY 755 permissions. In some servers, directories may need 750 permissions.
  • Wrong ownership (user & group issues) – The ownership of the file should be set to “USER : ApacheUser” or “USER : USER” depending on Apache’s configuration.
  • Incorrect encoding – Files uploaded in Binary mode will fail execution, and should be re-uploaded as ASCII.

Almost 80% of error 500 issues would be solved by these fixes.

This article is about the rest 20% of causes which are hard to find and fix.

Uncommon causes for Apache CGI Internal Server Error

500 Internal Server Error is a web server’s way of saying, “Something has gone wrong when I tried to display the page. Not sure what.

If it is not permission or ownership issues, it could be anything from application bugs & Apache misconfigurations to firewall blocks & file system errors.

Here are the top 10 uncommon issues we’ve seen in our course of work.

1. Missing modules

Web applications rely on a lot of PHP or Perl “modules” for specific functions.

Some such modules are part of a standard server setup, but many are not.

We’ve seen that after a migration or a during a new website setup, scripts often fail because all required modules are not present.

The error log will say there are “undefined” functions or “methods” do not exist.

To fix this, we go through the app requirement specifications, and install all missing modules.

2. Network timeouts (of API calls, remote scripts, etc.)

Some web apps get data from remote servers (eg. weather data).

If for some reason this connection to the remote server is interrupted, the web app will wait for a while and then show a time-out error.

Apache then reports this status as an Error 500.

This issue can be hard to troubleshoot as it might not leave a log entry.

We detect timeout issues by inspecting long pending outgoing connections, and fix it by disabling the app feature that requires the outbound connections.

3. Old program (compiler) paths

The first line in every CGI app (called Shebang) contains the path to the program that’s supposed to execute it.

For eg. Perl scripts have this path:

But this path can differ based on operating system vendors, and custom compilation settings.

So, the script will look for the program file in a particular location, and if it’s not found there, the script will show an Error 500.

Two effective methods are:

  • Use the paths defined in the server environment – The paths of all programs are stored in the server’s “environment” variable. So, we change the first line by calling the environment, like so:
    • #!/usr/bin/env perl
    • This will make sure that no matter where Perl is setup, the path will be available to the script.
  • Define the program paths in Apache config – Use the “AddHandler” and “Action” directives of Apache to execute all files with the right program. For eg. here’s how to setup PHP as a CGI:
    • AddHandler application/x-httpd-php5 php
    • Action application/x-httpd-php5 /local-bin/php-cgi

4. Errors in application code

Website owners can make small errors like deleting a “;” or inserting a stray character while editing application or configuration files.

This will result in the application failing to execute, but Apache will only spit out the cryptic “Internal Server Error” message.

We detect such issues by analyzing the log files, and resolve it by either fixing the code error, or by disabling the plugin / addon / theme that’s causing the error.

5. Old config files with wrong module paths

Websites are often customized for the server’s environment and program paths.

When sites are migrated, their configuration files will contain these old paths which might not be compatible with the new server.

We’ve seen cases where web applications use custom configuration files (say php.ini) to load library functions. This will fail when the path changes in a new server.

In such cases we remove the hard-coded program paths and instead use environment variables to automatically acquire program locations.

6. Security restrictions (Web application firewall, SELinux, etc.)

Most servers these days have Web Application Firewalls such as mod_security or ComodoWAF.

These firewalls can cause an Error 500 if it interprets a page request as an attack.

For eg. we’ve seen web apps failing because an external file calls were interpreted as a Remote File Inclusion attack by mod_security.

In such cases, we create custom firewall exclusion rules so that the app will no longer be blocked, while the server security is not affected.

Changing SELinux setting from “Enforcing” to “Permissive” has also helped us fix this error.

7. No Exec (no execution) restriction on the partition

CGI apps are executed as programs.

For that it needs something called an “Execute” privilege.

This “Execute” privilege is turned off for public accessible partitions such as “/tmp” and data-store partitions such as “/backup” to prevent malware execution.

We’ve seen cases where this “Execute” bit is turned off for website homes, thereby causing the script execution to fail.

We restore exec by:

  • # mount -o remount,exec /home

8. Apache & .htaccess misconfiguration (no ExecCGI, no AllowOverride, etc.)

Apache needs to know which directories contain CGI scripts.

That is denoted using the directive “ExecCGI”.

For eg. to denote /cgi-bin/ as a CGI directory, Apache should be configured with:

In some servers we’ve seen “ExecCGI” disabled in cgi-bin due to misconfiguration in either Apache conf file or an .htaccess in the parent directory.

Similarly, we’ve seen CGI related directives in .htaccess becoming ineffective because .htaccess was not enabled through an “AllowOverride” directive in Apache config.

All this can result in a failed script execution, and consequently an Error 500.

9. Wrong permissions on home directory

CGI directories are usually placed within the home directory. For eg. the path to a cgi-bin in cPanel servers is:

Many webmasters take care to change the permission of the cgi-bin directory and the web application directories to 755, but forget to check the home directory’s permissions.

In some Apache configurations (eg. when using SuExec), the home directory should also have 755 permissions. Anything other than that (eg. 777), will cause the script execution to fail.

So, one of the first things we check along with script file permissions is to check the permissions of all directories in the file’s path.

We set all of it just right to make sure the script executes without errors.

In some shared servers, security is enforced by confining each user to a jailed environment.

This prevents one user from accessing the files of any other user.

But such environments can break softlinks to program files.

For eg. if programs are stored in “/opt/php/bin/” and it is linked to from “/usr/bin/php/”, those references can get broken.

These are pretty rare cases, and we fix it by re-configuring the server (or site) to use the right path instead of softlinks.

Conclusion

Incorrect permission and ownership settings are the biggest causes for Apache CGI Internal Server Errors. But, there are more issues that can cause this error. Today we’ve covered the top 10 uncommon causes for this error as seen by our Support Engineers.

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.

Nice.
Very useful thanks. I’ve bookmarked so pls keep this current where necessary.
Cheers

Hello Honey,
Glad to know that post was useful 🙂

Источник

I am running Apache/2.4.10 (Ubuntu) and I was trying to run CGI scripts with the following configurations.

/etc/apache2/apache2.conf

With the following

Mutex file:${APACHE_LOCK_DIR} default
PidFile ${APACHE_PID_FILE}
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
HostnameLookups Off
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
Include ports.conf
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

AccessFileName .htaccess

<FilesMatch "^.ht">
    Require all denied
</FilesMatch>

LogFormat "%v:%p %h %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i"" vhost_combined
LogFormat "%h %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i"" combined
LogFormat "%h %l %u %t "%r" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

IncludeOptional conf-enabled/*.conf
IncludeOptional sites-enabled/*.conf

###################################################################
#########     Adding capaility to run CGI-scripts #################
ServerName localhost
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
Options +ExecCGI
AddHandler cgi-script .cgi .pl .py

And the /etc/apache2/conf-available/serve-cgi-bin.conf

<IfModule mod_alias.c>
    <IfModule mod_cgi.c>
        Define ENABLE_USR_LIB_CGI_BIN
    </IfModule>

    <IfModule mod_cgid.c>
        Define ENABLE_USR_LIB_CGI_BIN
    </IfModule>

    <IfDefine ENABLE_USR_LIB_CGI_BIN>
        #ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        #<Directory "/usr/lib/cgi-bin">
        #   AllowOverride None
        #   Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        #   Require all granted
        #</Directory>

        ## cgi-bin config
        ScriptAlias /cgi-bin/ /var/www/cgi-bin/
            <Directory "/var/www/cgi-bin/">
                AllowOverride None
                Options +ExecCGI 
            </Directory>

    </IfDefine>
</IfModule>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

I have my cgi-script in the directory /var/www/cgi-bin

with the contents in hello.py and made it executable.

#!/usr/bin/env python

import cgitb
    cgitb.enable()    print("Content-Type: text/html;charset=utf-8")

print "Content-type:text/htmlrnrn"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'

I also did sudo a2enmod cgi as suggested here Apache2.4.7 on Ubuntu 14.04 won’t execute Python cgi file. The site displays python code instead

When I try to run the script by going to http://localhost/cgi-bin/hello.py I am getting a 500 Internal Server error.

Any help would be greatly appreciated! Thanks

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

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

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»;

Понравилась статья? Поделить с друзьями:
  • Ubuntu amdgpu error
  • Ubuntu advantage tools error
  • Uboot partition system download buffer data transfer error
  • Uboot partition boot download buffer data transfer error
  • Uboot get result diskinitial error что это