How do you even look at the web.config file? I don’t know where to go to turn custom errors off…help!
I tried command prompt and java script….can any one help me?
tvanfosson
525k99 gold badges698 silver badges795 bronze badges
asked Dec 10, 2008 at 15:33
1
Keep in mind that IIS errors and asp.net errors are two separate things,
For remote requests, by default IIS has custom errors enabled, what that means is if you are returning a none 200 response from your application, IIS will discard the body you were sending back and replace it with its own custom page. which can be pretty troubling if you are hosting a REST service that needs to return error details to the client as json or XML.
to turn off ASP.net custom errors use customErrors Element (ASP.NET Settings Schema)
to turn off IIS custom errors use IIS HTTP Errors httpErrors
Lee Taylor
7,76116 gold badges34 silver badges49 bronze badges
answered Jun 18, 2012 at 18:22
kay.onekay.one
7,6226 gold badges55 silver badges74 bronze badges
3
Run the Internet Information Services (IIS) Manager tool from the Administrative Tools (on the start menu if admin tools are enabled there). Open up the system, and right click on your web site. Select Properties. Choose the ASP.NET tab. Click on «Edit Configuration». Click the Custom Errors tab. Select Off for custom error mode.
Or navigate to the folder containing your application and open the web.config file in a text editor and edit by hand, and change the custom errors tag to <customErrors mode=»Off» />.
answered Dec 10, 2008 at 15:47
tvanfossontvanfosson
525k99 gold badges698 silver badges795 bronze badges
Per the MSDN documentation the valid values for mode are:
On: Specifies that custom errors are enabled. If no defaultRedirect attribute is specified, users see a generic error. The custom errors are shown to the remote clients and to the local host.
Off Specifies that custom errors are disabled. The detailed ASP.NET errors are shown to the remote clients and to the local host.
RemoteOnly Specifies that custom errors are shown only to the remote clients, and that ASP.NET errors are shown to the local host. This is the default value.
The default is RemoteOnly.
answered Dec 10, 2008 at 15:54
Jim AndersonJim Anderson
3,6022 gold badges24 silver badges21 bronze badges
Я думаю, что обнаружил ошибку в системе страниц ошибок IIS.
Примечание: — Я не использую страницы ошибок .NET — для этого параметра установлено значение Выкл.
Проблема:
Когда настраиваемая страница ошибки настроена для кода ответа 500.100 (классический ASP), IIS всегда отправляет настраиваемую страницу ошибки, даже если для параметра errorMode установлено значение Подробно . Единственный способ заставить IIS отправить ошибку — явно удалить запись в файле web.config.
НАПРИМЕР:
<remove statusCode="500" subStatusCode="100"/>
or
<clear/>
Примечание — следующее не работает (работает для всех остальных кодов):
<remove statusCode="500" subStatusCode="-1"/>
Мой сценарий:
- IIS 8 (я не знаю, существует ли проблема в более старых версиях IIS)
- Веб-сайт под управлением .NET 2.0 — классический конвейер
- Для делегирования функций на страницах ошибок установлено значение только для чтения
- Настройка страницы ошибок в IIS следующим образом (из-за вышеупомянутого делегирования функции эти записи отсутствуют в web.config):
- 404 — /path/to/404.htm — ExecuteURL
- 500 — /path/to/500.htm — ExecuteURL
- 500.100 — /path/to/500.htm — ExecuteUrl
Отключение пользовательских ошибок:
Все, что мне нужно сделать, чтобы отключить пользовательские ошибки, это:
- Загрузить IIS
- Загрузить
Error Pages - Нажмите
Edit Feature Settings - Выберите
Detailed Errors
Это успешно работает для всех кодов кроме ошибок Classic ASP 500 (код состояния 500.100).
Единственный способ получить правильную классическую ошибку ASP — это настроить следующее (что требует, чтобы я изменил делегирование функции на чтение / запись):
<system.webServer>
<httpErrors errorMode="Detailed">
<clear/>
OR
<remove statusCode="500" subStatusCode="100"/>
</httpErrors>
</system.webServer>
Резюме
Похоже, что если настроена настраиваемая страница ошибок 500.100, то установка для Подробных ошибок значения true не работает для ошибок Classic ASP 500.
Это ошибка или я что-то упускаю?
2 ответа
Лучший ответ
Это известная ошибка, которую мы также получаем и работаем над ее устранением, удаляя ошибку 500 и вместо этого ссылаясь на нашу настраиваемую страницу из части конфигурации «когда вы можете найти что-нибудь еще для отправки».
(Я не могу вспомнить, как это называется)
1
back_ache
22 Апр 2013 в 15:49
Попробуйте изменить свой web.config таким образом (у меня это сработало с IIS 7.5).
Заменить строку
<httpErrors errorMode="Detailed">
С участием
<httpErrors existingResponse="PassThrough" errorMode="Detailed">
Это связано с тем, что по умолчанию IIS7 перехватывает коды состояния HTTP, такие как 4xx и 5xx, генерируемые приложениями, находящимися дальше по конвейеру.
0
Gustavo
27 Июн 2013 в 12:49
- Remove From My Forums
-
Вопрос
-
Подскажите как убрать подробные описания ошибок в 404,403 и т.д. страницах IIS? Я ограничиваю по IP доступ к веб сервисам и когда вылезает
подробная простыня с описанием где что лежит на моем сервере это плохо. Ладно бы она вылезала для локальных пользователей, но она вылезает и для тех кто щаходит с внешнего IP через шлюз. В стандартных настройках не могу найти.
Ответы
-
Здравствуйте,
в IIS Manager в настройках Error Pages -> «Detailed errors for local request and custom error pages for remote requests » если речь идет о ASP.Net, также просмотрите custom errors в случае , если веб-приложение выдает детальную ошибку.
Либо закомментируйте/удалите в файле web.config в случае, если ранее прописывали:
<system.webServer> <!-- <httpErrors errorMode="Detailed" /> --> </system.webServer>
Best Regards, Andrei …
MCP-
Изменено
17 февраля 2016 г. 7:26
добавлено -
Помечено в качестве ответа
Petko KrushevMicrosoft contingent staff, Moderator
2 марта 2016 г. 11:22
-
Изменено
By default, the IIS server is set to show detailed errors for local requests only, whereas it displays a custom error page for remote requests. This is done for security reasons, since detailed errors could reveal potentially detailed technical information about the web server and website.
Contents
- Why are detailed errors important?
- Enabling detailed errors using the IIS manager
- Enabling detailed errors using the web.config file
- Author
- Recent Posts
Surender Kumar has more than twelve years of experience in server and network administration. His fields of interest are Windows servers, Active directory, PowerShell, web servers, networking, Linux, virtualization, and Kubernetes. He loves writing for his blog.
Latest posts by Surender Kumar (see all)
- Kubernetes DaemonSets — Wed, Sep 6 2023
- Static Pods in Kubernetes — Fri, Sep 1 2023
- Encrypt Kubernetes Secrets at rest — Mon, Aug 28 2023
The detailed errors also reveal HTTP substatus codes, which are helpful in debugging complex issues. The bad guys out there could use this information to conduct attacks on a web server or website. That is why the IIS server only shows a custom error page for remote requests by default.
Why are detailed errors important?
As discussed above, detailed errors are important when you want to debug a problem in a website hosted on a server running IIS. The custom error page shows an error message that is usually ambiguous. Let’s have a look at the two screenshots below:
403 Forbidden Access is denied error using custom error page
The above screenshot shows a typical 403 – Forbidden: Access is denied error using the custom error page displayed by IIS. It is not very helpful for website administrators. Now, let’s have a look at the following screenshot:
403.14 Forbidden error with detailed error mode enabled
This screenshot shows the same error with detailed error mode enabled. Now, it shows plenty of useful information that an administrator can use to identify the cause and fix the problem.
Enabling detailed errors using the IIS manager
To enable detailed errors:
- Open the IIS manager by pressing WinKey+R, typing inetmgr, and pressing Enter.
- Expand the Sites node and select the website for which you want to enable detailed errors.
- Under the IIS section in the Features View, double-click Error Pages (see the following screenshot).
Locating the error pages section in the IIS manager
- In the Actions pane on the right, click Edit Feature Settings.
Enabling detailed errors in IIS manager
- In Error Responses, you will see three options:
- Custom error pages
- Detailed errors
- Detailed errors for local requests and custom error pages for remote requests (default)
- Now select either the second or third option and click OK.
Viewing the detailed error modes in IIS
Since you can directly access the web server using remote desktop, selecting the third option is best. Now, you can open the web browser on the server itself and try to load the problematic webpage to see a detailed error page containing more technical information. By doing this, you’re not enabling the bad guys out there to view the detailed information, since the detailed error is only displayed for local requests.
Enabling detailed errors using the web.config file
There are situations in which you cannot use the IIS manager to enable detailed errors. For example, if your website is hosted on a shared hosting site, you won’t have access to the IIS manager. In such scenarios, you could enable detailed errors using the web.config file, which is usually located in the root directory of the website. Just add the following line inside the <system.webServer> tag:
<httpErrors errorMode="Detailed" />
Enabling detailed errors using web.config file
Remember that by adding this line to the web.config file, you are forcing IIS to throw the detailed errors for local or remote requests.
Subscribe to 4sysops newsletter!
Once you identify the root cause of the problem, it is always recommended to disable detailed errors to prevent your website from revealing sensitive information.
Хостинг-провайдеры нередко отключают или блокируют вывод всех ошибок и предупреждений. Такие ограничения вводятся не просто так. Дело в том, что на рабочих серверах крайне не рекомендуется держать ошибки в открытом доступе. Информация о неисправностях может стать «наживкой» для злоумышленников.
При этом в процессе разработки сайтов и скриптов, очень важно отслеживать возникающие предупреждения. Знать о сбоях и неисправностях также важно и системным администраторам — это позволяет предотвратить проблемы на сайте или сервере.
Самый оптимальный вариант — не просто скрыть показ ошибок, но и настроить запись о них в логах. Это позволит отслеживать предупреждения и не подвергать сервер угрозе.
В статье мы расскажем, как включить и отключить через .htaccess вывод ошибок php, а также двумя другими способами — через скрипт PHP и через файл php.ini.
Обратите внимание: в некоторых случаях изменение настроек вывода возможно только через обращение в техническую поддержку хостинга.
Через .htaccess
Перейдите в каталог сайта и откройте файл .htaccess.
Вариант 1. Чтобы включить вывод, добавьте следующие строки:
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
Чтобы отключить ошибки PHP htaccess, введите команду:
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
Также выключить .htaccess display errors можно командой:
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0
Через логи PHP
Если вам нужно проверить или выключить ошибки только в определенных файлах, это можно сделать с помощью вызова PHP-функций.
Вариант 1. Чтобы включить вывод, используйте команду error_reporting. В зависимости от типа ошибок, которые вы хотите увидеть, подставьте нужное значение. Например, команда для вывода всех ошибок будет выглядеть так:
А для всех типов, исключая тип Notice, так:
error_reporting(E_ALL & ~E_NOTICE)
Чтобы отключить вывод, введите команду:
Чтобы отключить логирование повторяющихся ошибок, введите:
# disable repeated error logging
php_flag ignore_repeated_errors on
php_flag ignore_repeated_source on
Вариант 2. Чтобы проверить конкретный кусок кода, подойдет команда ниже. В зависимости от типа ошибок, которые вы хотите увидеть, в скобках подставьте нужное значение. Например, команда для вывода всех ошибок будет выглядеть так:
ini_set('display_errors', 'On')
error_reporting(E_ALL)
После этого в консоли введите:
ini_set('display_errors', 'Off')
Вариант 3. Ещё один из вариантов подключения через скрипт:
php_flag display_startup_errors on
php_flag display_errors on
Для отключения укажите:
php_flag display_startup_errors off
php_flag display_errors off
Вариант 4. Чтобы настроить вывод с логированием через конфигурацию веб-сервера, введите:
- для Apache —
ErrorLog «/var/log/apache2/my-website-error.log», - для Nginx —
error_log /var/log/nginx/my-website-error.log.
Подробнее о других аргументах читайте в документации на официальном сайте php.net.
Через файл php.ini
Настроить отслеживание также можно через файл php.ini. Этот вариант подойдет, когда отображение или скрытие ошибок нужно настроить для всего сайта или кода. Обратите внимание: возможность настройки через файл php.ini есть не у всех, поскольку некоторые хостинг-провайдеры частично или полностью закрывают доступ к файлу.
Вариант 1. Если у вас есть доступ, включить вывод можно командой:
После этого нужно перезагрузить сервер:
sudo apachectl -k graceful
Вариант 2. Чтобы включить вывод, используйте команду error_reporting. В зависимости от типа ошибок, которые вы хотите увидеть, после знака = подставьте нужное значение. Например, команда для вывода всех ошибок будет выглядеть так:
error_reporting = E_ALL
display_errors On
После ввода перезагрузите сервер:
sudo apachectl -k graceful
Чтобы скрыть отображение, во второй строке команды укажите Оff вместо On:
Теперь вы знаете, как настроить не только через PHP и php.ini, но и через htaccess отображение ошибок.
Помогла ли вам статья?
Спасибо за оценку. Рады помочь 😊
👍






