Iis ошибка 401

Как исправить ошибку сервера 401 Unauthorized (Отказ в доступе): пошаговая инструкция. Причины появления ошибки 401. Как устранить проблему со стороны и клиента и владельца сайта.

Появление сообщения об ошибке 401 Unauthorized Error («отказ в доступе») при открытии страницы сайта означает неверную авторизацию или аутентификацию пользователя на стороне сервера при обращении к определенному url-адресу. Чаще всего она возникает при ошибочном вводе имени и/или пароля посетителем ресурса при входе в свой аккаунт. Другой причиной являются неправильные настройки, допущенные при администрировании web-ресурса. Данная ошибка отображается в браузере в виде отдельной страницы с соответствующим описанием. Некоторые разработчики интернет-ресурсов, в особенности крупных порталов, вводят собственную дополнительную кодировку данного сбоя:

  • 401 Unauthorized;
  • Authorization Required;
  • HTTP Error 401 – Ошибка авторизации.

Попробуем разобраться с наиболее распространенными причинами возникновения данной ошибки кода HTTP-соединения и обсудим способы их решения.

Причины появления ошибки сервера 401 и способы ее устранения на стороне пользователя

При доступе к некоторым сайтам (или отдельным страницам этих сайтов), посетитель должен пройти определенные этапы получения прав:

  1. Идентификация – получение вашей учетной записи («identity») по username/login или email.
  2. Аутентификация («authentic») – проверка того, что вы знаете пароль от этой учетной записи.
  3. Авторизация – проверка вашей роли (статуса) в системе и решение о предоставлении доступа к запрошенной странице или ресурсу на определенных условиях.

Большинство пользователей сохраняют свои данные по умолчанию в истории браузеров, что позволяет быстро идентифицироваться на наиболее часто посещаемых страницах и синхронизировать настройки между устройствами. Данный способ удобен для серфинга в интернете, но может привести к проблемам с безопасностью доступа к конфиденциальной информации. При наличии большого количества авторизованных регистрационных данных к различным сайтам используйте надежный мастер-пароль, который закрывает доступ к сохраненной в браузере информации.

Наиболее распространенной причиной появления ошибки с кодом 401 для рядового пользователя является ввод неверных данных при посещении определенного ресурса. В этом и других случаях нужно попробовать сделать следующее:

  1. Проверьте в адресной строке правильность написания URL. Особенно это касается перехода на подстраницы сайта, требующие авторизации. Введите правильный адрес. Если переход на страницу осуществлялся после входа в аккаунт, разлогинитесь, вернитесь на главную страницу и произведите повторный вход с правильными учетными данными.
  2. При осуществлении входа с сохраненными данными пользователя и появлении ошибки сервера 401 проверьте их корректность в соответствующих настройках данного браузера. Возможно, авторизационные данные были вами изменены в другом браузере. Также можно очистить кэш, удалить cookies и повторить попытку входа. При удалении истории браузера или очистке кэша потребуется ручное введение логина и пароля для получения доступа. Если вы не помните пароль, пройдите процедуру восстановления, следуя инструкциям.
  3. Если вы считаете, что вводите правильные регистрационные данные, но не можете получить доступ к сайту, обратитесь к администратору ресурса. В этом случае лучше всего сделать скриншот проблемной страницы.
  4. Иногда блокировка происходит на стороне провайдера, что тоже приводит к отказу в доступе и появлению сообщения с кодировкой 401. Для проверки можно попробовать авторизоваться на том же ресурсе с альтернативного ip-адреса (например, используя VPN). При подтверждении блокировки трафика свяжитесь с провайдером и следуйте его инструкциям.

Некоторые крупные интернет-ресурсы с большим количеством подписчиков используют дополнительные настройки для обеспечения безопасности доступа. К примеру, ваш аккаунт может быть заблокирован при многократных попытках неудачной авторизации. Слишком частые попытки законнектиться могут быть восприняты как действия бота. В этом случае вы увидите соответствующее сообщение, но можете быть просто переадресованы на страницу с кодом 401. Свяжитесь с администратором сайта и решите проблему.

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

Ошибка 401 - отказ в доступе

Устранение ошибки 401 администратором веб-ресурса 

Для владельцев сайтов, столкнувшихся с появлением ошибки отказа доступа 401, решить ее порою намного сложнее, чем обычному посетителю ресурса. Есть несколько рекомендаций, которые помогут в этом:

  • Обращение в службу поддержки хостинга сайта. Как и в случае возникновения проблем с провайдером, лучше всего подробно описать последовательность действий, приведших к появлению ошибки 401, приложить скриншот.
  • При отсутствии проблем на стороне хостинг-провайдера можно внести следующие изменения в настройки сайта с помощью строки Disallow:/адрес проблемной страницы. Запретить индексацию страницам с ошибкой в «rоbоts.txt», после чего добавить в файл «.htассеss» строку такого типа:
Redirect 301 /oldpage.html http://site.com/newpage.html.

Где в поле /oldpage.html прописывается адрес проблемной страницы, а в http://site.com/newpage.html адрес страницы авторизации.

Таким образом вы перенаправите пользователей со всех страниц, которые выдают ошибку 401, на страницу начальной авторизации.

  • Если после выполнения предыдущих рекомендаций пользователи при попытках авторизации все равно видят ошибку 401, то найдите на сервере файл «php.ini» и увеличьте время жизни сессии, изменив значения следующих параметров: «session.gc_maxlifetime» и «session.cookie_lifetime» на 1440 и 0 соответственно.
  • Разработчики веб-ресурсов могут использовать более сложные методы авторизации и аутентификации доступа для создания дополнительной защиты по протоколу HTTP. Если устранить сбой простыми методами администрирования не удается, следует обратиться к специалистам, создававшим сайт, для внесения соответствующих изменений в код.

Хотя ошибка 401 и является проблемой на стороне клиента, ошибка пользователя на стороне сервера может привести к ложному требованию входа в систему. К примеру, сетевой администратор разрешит аутентификацию входа в систему всем пользователям, даже если это не требуется. В таком случае сообщение о несанкционированном доступе будет отображаться для всех, кто посещает сайт. Баг устраняется внесением соответствующих изменений в настройки.

Дополнительная информация об ошибке с кодом 401

Веб-серверы под управлением Microsoft IIS могут предоставить дополнительные данные об ошибке 401 Unauthorized в виде второго ряда цифр:

  • 401, 1 – войти не удалось;
  • 401, 2 – ошибка входа в систему из-за конфигурации сервера;
  • 401, 3 – несанкционированный доступ из-за ACL на ресурс;
  • 401, 501 – доступ запрещен: слишком много запросов с одного и того же клиентского IP; ограничение динамического IP-адреса – достигнут предел одновременных запросов и т.д.

Более подробную информацию об ошибке сервера 401 при использовании обычной проверки подлинности для подключения к веб-узлу, который размещен в службе MS IIS, смотрите здесь. 

Следующие сообщения также являются ошибками на стороне клиента и относятся к 401 ошибке:

  • 400 Bad Request; 
  • 403 Forbidden; 
  • 404 Not Found;
  • 408 Request Timeout.

Как видим, появление ошибки авторизации 401 Unauthorized не является критичным для рядового посетителя сайта и чаще всего устраняется самыми простыми способами. В более сложной ситуации оказываются администраторы и владельцы интернет-ресурсов, но и они в 100% случаев разберутся с данным багом путем изменения настроек или корректировки html-кода с привлечением разработчика сайта. 

In my previous post, you learned how to troubleshoot HTTP Error 503. Today, we will look into how to troubleshoot 401 – Unauthorized: Access is denied due to invalid credentials in Internet Information Services (IIS).

Contents

  1. 401 – Unauthorized
  2. How IIS authentication works
  3. Cause of error
  4. Debugging the error
  5. Resolving the error
  6. Common 401 substatus codes
  7. Conclusion
  • 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 penetration testing. He loves writing for his blog.

Latest posts by Surender Kumar (see all)

  • Extending LVM space in Ubuntu — Thu, Feb 2 2023
  • Backup in Proxmox VE — Thu, Jan 26 2023
  • Snapshots in Proxmox VE — Wed, Jan 25 2023

401 – Unauthorized

401 Unauthorized Access is denied due to invalid credentials

401 Unauthorized Access is denied due to invalid credentials

The 401 – Unauthorized: Access is denied due to invalid credentials error is a common access-related error that you may experience with a website hosted on IIS.

How IIS authentication works

The error itself indicates that it is caused by a failure to authorize access. Someone who is a beginner in IIS could find the error description «you do not have permission to view this directory or page using the credentials that you supplied» slightly confusing. If you think from an end user’s perspective, you might be wondering when you supplied any credentials while accessing the website. Well, this happened automatically on the server side. By default, every website hosted on IIS has anonymous authentication enabled.

If you open the IIS Manager, select your website, and then double-click Authentication under the IIS section in the Features view, you will see the various authentication modes (such as basic authentication, forms authentication, anonymous authentication, etc.) that are supported by IIS.

Viewing various authentication modes supported by a website in IIS

Viewing various authentication modes supported by a website in IIS

Each website has to have at least one authentication mode enabled and, by default, Anonymous Authentication mode enabled. Authentication is a mechanism that is used to verify the visitor’s identity to your website. See the following screenshot for reference:

Default authentication modes supported by a website in IIS

Default authentication modes supported by a website in IIS

Anonymous authentication allows visitors to access the public content of your website anonymously without having to supply any credentials. If you don’t want to use it, select the authentication mode, and then click Disable in the Actions pane on the right. To view or modify which credentials are used by anonymous authentication, click the Edit link on the right. You will see two options, as shown in the following screenshot:

View or modify the credentials used by anonymous authentication in IIS

View or modify the credentials used by anonymous authentication in IIS

By default, each website is set to use the IUSR user for anonymous user identity, which is a built-in account starting with IIS version 7. If you are using a custom username as the application pool identity, make sure you select the application pool identity option here. This way, you don’t have to worry about updating the user’s password in the website configuration over and over when the user’s password is changed.

Cause of error

The primary cause of the 401 – Unauthorized: Access is denied due to invalid credentials error is that you are using a custom username as the application pool identity. In simple terms, when you set the application pool to use a custom application pool identity (a custom username and password) rather than the default identity (which is ApplicationPoolIdentity), the Anonymous Authentication mode of the website continues using the IUSR user for authentication, which results in this error.

Debugging the error

As discussed in previous posts, the error page we saw above is a custom error page and does not reveal much helpful information for administrators. If you enable the detailed errors, you will see an error page with much detailed information, as shown in the following screenshot:

Error message 401.3 – You do not have permission to view this directory or page using the credentials you supplied (acc

Error message 401.3 – You do not have permission to view this directory or page using the credentials you supplied (access denied due to Access Control Lists)

The detailed error gave you the HTTP 401.3 status code, which will guide you in checking the access control permissions on the file system. Make sure that the user who is set as the application pool identity has the read and execute permissions on the website’s root directory. If the error persists, the most likely cause is incorrect anonymous user identity. The following screenshot shows the problematic scenario:

Mismatched application pool identity and anonymous authentication identity user in IIS

Mismatched application pool identity and anonymous authentication identity user in IIS

The screenshot shows a mismatched application pool identity and anonymous authentication identity on the website, which is causing the error. For a website to work properly, both should be the same.

Resolving the error

Now that you know the cause of the HTTP 401.3 status code, do the following to fix the error:

If you are using a custom username as the application pool identity, make sure that the user has read and execute permissions on the website’s root directory.

Ensuring that the custom application pool user has read and execute permissions on the root directory

Ensuring that the custom application pool user has read and execute permissions on the root directory

If you’re using the default ApplicationPoolIdentity for your application pool, make sure that the built-in IUSR user or IIS_IUSRS group has exactly the same permissions as shown in the screenshot below.

Ensuring that the default application pool identity has read and execute permissions on the root directory

Ensuring that the default application pool identity has read and execute permissions on the root directory

If the error persists, edit the Anonymous Authentication setting of your website, as explained in the How IIS authentication works section. Be sure it is set to use the Application pool identity. See the following screenshot for reference:

Modifying the anonymous authentication identity to match the application pool identity in IIS

Modifying the anonymous authentication identity to match the application pool identity in IIS

Common 401 substatus codes

The following table covers the most common HTTP 401 substatus codes, along with their possible causes and troubleshooting advice:

Subscribe to 4sysops newsletter!

Status Code Possible Cause Troubleshooting Advice
401.1 Logon failed The logon attempt failed, probably due to an invalid user name or password.
401.2 Logon failed due to server configuration The 401.2 status code indicates that there is a problem in the authentication configuration on the server.
401.3 Unauthorized due to ACL on resource We covered how to fix this error above.

Conclusion

I hope you’re enjoying this series of resolving common HTTP errors. In the next post, we will discuss how to fix the HTTP Error 403.14 – Forbidden error.

I have created site on my local machine that works fine on debug mode but when i put the site on local iis (7.5) of my machine i get

HTTP Error 401.1 — Unauthorized
You do not have permission to view this directory or page using the credentials that you supplied.

Authentication Settings
I have windows impersonation and windows authentication enabled and everything else in that section is disabled

All the folder have full permissions

Can anyone tell me what’s going on?

Luke Girvin's user avatar

Luke Girvin

13.1k8 gold badges63 silver badges84 bronze badges

asked Oct 8, 2010 at 16:36

devforall's user avatar

2

As a quick and dirty fix, grant the IIS_IUSRS group Read/Execute or Modify permissions to your web folder… BUT DON’T DO THIS ON AN INTERNET FACING SERVER, read on….

To fix this properly you should grant the Application Pool Identity for your site Read/Execute or Modify permissions to your application’s web folder. To do this:

  1. Open IIS Manager, navigate to your website or application folder where the site is deployed to.
  2. Open Advanced Settings (it’s on the right hand Actions pane).
  3. Note down the Application Pool name then close this window
  4. Double click on the Authentication icon to open the authentication settings
  5. Disable Windows Authentication
  6. Right click on Anonymous Authentication and click Edit
  7. Choose the Application pool identity radio button the click OK
  8. Select the Application Pools node from IIS manager tree on left and select the Application Pool name you noted down in step 3
  9. Right click and select Advanced Settings
  10. Expand the Process Model settings and choose ApplicationPoolIdentity from the «Built-in account» drop down list then click OK.
  11. Click OK again to save and dismiss the Application Pool advanced settings page
  12. Open an Administrator command line (right click on the CMD icon and select «Run As Administrator». It’ll be somewhere on your start menu, probably under Accessories.
  13. Run the following command:

icacls <path_to_site> /grant "IIS APPPOOL<app_pool_name>"(CI)(OI)(M)

For example:

icacls C:inetpubwwwrootmysite /grant "IIS APPPOOLDEFAULTAPPPOOL":(CI)(OI)(M)

If all is good icacls.exe will report:

processed file: c:inetpubwwwrootmysite
Successfully processed 1 files; Failed processing 0 files

answered Oct 8, 2010 at 17:33

Kev's user avatar

KevKev

117k52 gold badges297 silver badges382 bronze badges

7

In my case this had nothing to do with permissions. This is the «loopback check» protection. The problem was because I was connecting from the local machine that had the IIS.

Symptoms are: You connect and you get a browser prompt to insert credentials 3 times, then an HTTP 401.1 error.

Testing from a different computer works well.

Some sites will tell you to disable the «loopback check», but instead you have to add the FQDN domain you’re connecting to to a whitelist, as described in this serverfault response:

https://serverfault.com/a/485011/415362

answered Feb 13, 2020 at 14:50

ciencia's user avatar

cienciaciencia

4364 silver badges9 bronze badges

3

i also had the same issue. i simply remove the application. created a new floder and hosted it again. problem solved.

answered Jan 10, 2017 at 8:28

sasireka's user avatar

1

Somewhat late in coming, but an alternative that I sometimes forget is time difference. In a domain environment, run «Net Time /SET» to synchronise with the AD Box.

Additional Reading:

For all of this to work and to ensure security, the domain controllers and clients must have the same time. Windows operating systems include the Time Service tool (W32Time service). Kerberos authentication will work if the time interval between the relevant computers is within the maximum enabled time parameters. The default is five minutes. You can also turn off the Time Service tool and install a third-party time service. Of course, if you have problems authenticating, you should make sure that the time is correct for the domain controllers and the client that is experiencing the problem.
(Source: https://sourcedaddy.com/windows-7/server-authentication.html)

Heavier Reading:

…. In addition, IT professionals should understand how Windows Time Service works because Kerberos security is highly dependent on time services. ….
(Source: https://redmondmag.com/articles/2012/02/01/understanding-the-essentials-of-the-kerberos-protocol.aspx )

answered Aug 18, 2018 at 14:51

Anthony Horne's user avatar

Anthony HorneAnthony Horne

2,5062 gold badges32 silver badges51 bronze badges

Дано: Windows Server 2012 R2
Ошибка: HTTP 401.1 — Unauthorized: Logon Failed при авторизации на сайте (IIS)

Для каких случаев данное решение:

  • У Вас IIS версии 5.1 или выше
  • Используется доменная аутентификация для сайта (Windows Authentication)
  • Вы пытаетесь локально (на той же машине, где находится сам IIS) открыть сайт, у которого применена доменная авторизация
  • Вы пытаетесь локально обратиться к сервисам на IIS по доменной авторизации (например, если на этом же сервере установлен кластер 1С, а в серверном коде производится попытка обратиться к сервисам на локальном IIS)

В этих случаях получаем примерно такое сообщение об ошибке:

HTTP Error 401.1 — Unauthorized 
You do not have permission to view this directory or page using the credentials that you supplied.

Detailed Error Information:
Module    WindowsAuthenticationModule
Notification    AuthenticateRequest
Handler    1C Web-service Extension
Error Code    0xc000006d

Requested URL    Тут проблемный URL
Physical Path    c:inetpubwwwrootwshs
Logon Method    Not yet determined
Logon User    Not yet determined

В логах сервера также можно увидеть следующее сообщение:

An account failed to log on.
Subject:
Security ID: NULL SID
Account Name:
Account Domain:
Logon ID: 0x0
Logon Type: 3
Account For Which Logon Failed:
Security ID: NULL SID
Account Name: username
Account Domain: domainname
Failure Information:
Failure Reason: An Error occured during Logon.
Status: 0xC000006D
Sub Status: 0x0
Process Information:
Caller Process ID: 0x0
Caller Process Name:
Network Information:
Workstation Name: SRV-PRG
Source Network Address:
Source Port:
Detailed Authentication Information:
Logon Process:
Authentication Package: NTLM
Transited Services:
Package Name (NTLM only):
Key Length: 0

Как вариант решения: в реестре необходимо указать хост, к которому Вы разрешаете подключаться при помощи доменной аутентификации.

Для этого находим в реестре следующую ветку:


HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlLsaMSV1_0

Создаем новый ключ:
— Тип — Multi-String Value
— Имя — BackConnectionHostNames
— В значениях ключа указать нужные адреса.

После настройки — перезагрузите IIS.

Если Вам понравилась статья, пожалуйста, поставьте лайк, сделайте репост или оставьте комментарий. Если у Вас есть какие-либо замечания, также пишите комментарии.

  • Remove From My Forums
  • Question

  • User1377211471 posted

    I am getting the below error message in my windows 2008 server when I am trying to browse the default website in the local server. Anonymous auth is disabled. Windows auth is enabled.

    Error Summary

    HTTP Error 401.2 — Unauthorized

    You are not authorized to view this page due to invalid authentication headers.

    <FIELDSET><LEGEND>Detailed Error Information</LEGEND>

    Module IIS Web Core
    Notification AuthenticateRequest
    Handler StaticFile
    Error Code 0x80070005
    Requested URL http://localhost:80/
    Physical Path C:inetpubwwwroot
    Logon Method Not yet determined
    Logon User Not yet determined
    Failed Request Tracing Log Directory C:inetpublogsFailedReqLogFiles

    </FIELDSET>

    <FIELDSET><LEGEND>Most likely causes:</LEGEND>

    • No authentication protocol (including anonymous) is selected in IIS.
    • Only integrated authentication is enabled, and a client browser was used that does not support integrated authentication.
    • Integrated authentication is enabled and the request was sent through a proxy that changed the authentication headers before they reach the Web server.
    • The Web server is not configured for anonymous access and a required authorization header was not received.
    • The «configuration/system.webServer/authorization» configuration section may be explicitly denying the user access.

    </FIELDSET>

    <FIELDSET><LEGEND>Things you can try:</LEGEND>

    • Verify the authentication setting for the resource and then try requesting the resource using that authentication method.
    • Verify that the client browser supports Integrated authentication.
    • Verify that the request is not going through a proxy when Integrated authentication is used.
    • Verify that the user is not explicitly denied access in the «configuration/system.webServer/authorization» configuration section.
    • Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click
      here.

    </FIELDSET>

    <FIELDSET><LEGEND>Links and More Information</LEGEND>This error occurs when the WWW-Authenticate header sent to the Web server is not supported by the server configuration. Check the authentication method for the resource, and
    verify which authentication method the client used. The error occurs when the authentication methods are different. To determine which type of authentication the client is using, check the authentication settings for the client.

    View more information »

    Microsoft Knowledge Base Articles:

    </FIELDSET>

    Ther are no webproxy, IE7 is enable for local intranet connection.

title author description ms.date ms.assetid msc.legacyurl msc.type

How to Use HTTP Detailed Errors in IIS 7.0

rick-anderson

Every Web-Site Administrator or Web Developer has seen ‘404 — File not found’, ‘401 — Unauthorized’ or ‘500 — Server Error’ messages in his browser. This ar…

12/12/2007

33897393-97b8-4ee1-836f-25b1348dc3a3

/learn/troubleshoot/diagnosing-http-errors/how-to-use-http-detailed-errors-in-iis

authoredcontent

by IIS Team

Introduction

Every Web-Site Administrator or Web Developer has seen «404 — File not found», «401 — Unauthorized» or «500 — Server Error» messages in his browser. This article helps you understand how and why IIS generates these errors and how they can be configured.

Many might think that generating error messages does not seem to justify a full article. But there is more to errors than meets the eye. Error messages are a sensitive topic, because every error reveals more about your web-site than you might want revealed. The more information someone can gather about your site, the likelier it is that you will be hacked. A search for «google hacking» or «cross-site scripting» reveals a wealth of information on this topic.

However, error messages are also a valuable tool to troubleshoot problems. Developers and Web-Site Administrators require as much detail as possible when an error occurs. Ideally the error message gives recommendations on how to fix the problem. Here is how IIS addresses these fundamentally opposed goals.

Errors, What Errors?

This article talks about HTTP errors as specified in the HTTP RFC (RFC 2616 — section 6.1.1). An HTTP error is always expressed by sending a response with a status code greater than 400 back to the requesting client.

Client Errors

Status codes between 400 and 500 specify an error that the client made, e.g. bad syntax or a request to a resource that doesn’t exist. You can try this by requesting a bogus URL from the web-site of your choice, for example: http://<IIS7Server>/this_resource_does_not_exist. You get a «404 — File not found» error.

Server Errors

Status codes starting with 500 are errors caused by the server. The most common causes for 500 errors on IIS systems are:

  • An ASP or ASPX page that contains a syntax error
  • The web server configuration or the application configuration cannot be read or is invalid
  • The site is stopped

It is important to note that browsers like IE often replace errors returned from a web server with their own errors. This makes troubleshooting harder. In IE you can turn this feature off. Go to the «Tools» menu, select «Internet Options», click the «Advanced» tab and find the «Show friendly HTTP error messages» check box and uncheck it. To see the raw response, use HTTP tools like WFETCH in the IIS 6.0 Resource Kit (see «Related Links»).

HTTP Errors in IIS

There are two things that can happen when the httpError module (custerr.dll) encounters an error:

  • A custom error is generated
  • A detailed error is generated

Custom errors are error pages that the regular users of your web-site see. They contain a brief error description of why the error happened, but nothing else. Here is the custom error generated when you request a resource that does not exist, for example: http://<IIS7Server>/this_resource_does_not_exist

Screenshot of the the H T T P Error 404 file or directory not found webpage in Internet Explorer.

Detailed errors are intended for local administrators and developers. They are supposed to provide information that helps to immediately fix the problem. Here is an example of the same request, but now returning a Detailed Error:

Screenshot of the Server Error in Default Web Site Application webpage, showing a Cause and Solution section for the error.

This is dangerous, because Detailed Errors contain information about the inner workings of your web-site. Only trusted personnel should see a Detailed Error. The only way to ensures this is to only generate a detailed error if the request comes from the local machine. As soon as the request is not local, a custom error is generated. Look at the following flow diagram:

Diagram of the Status Substatus, Entity Body, and Set Error's path of creating a detailed error.

Data Flow

First: Error check

The httpError module receives a notification if a response is about to be sent (RQ_SEND_RESPONSE notification). The httpError module checks the status code of this response and immediately returns if the status code is not greater than 400.

Second: Custom Error or Detailed Error

The next check is determined by the request origin (is the request a local or remote request) and the setting of the errorMode property. The errorMode property is set to DetailedLocalOnly, which means that Custom Errors are generated for every remote request. If errorMode is set to «Custom», then all error responses will become Custom Error. If errorMode is set to «Detailed» all error responses will become Detailed Errors. The following table clarifies this behavior:

errorMode Request origin Action
DetailedLocalOnly (default) Local Detailed Error
DetailedLocalOnly (default) Remote Custom Error
Custom Local Custom Error
Custom Remote Custom Error
Detailed Local Detailed Error
Detailed Remote Detailed Error

If the httpError module determines that a Custom Error must be generated, it looks into its configuration to see if it can find a matching error. If a match is found, it sends the static file, redirects the request or executes the URL specified. If no match can be found, IIS send a basic one-line message containing the status code. The next section explains the Custom Error configuration in detail.

If custerr.dll determines that a Detailed Error must be generated, another check is needed. IIS does not touch the response if a module overrode the entity of the response with its own error description. It might contain valuable information. ASP.NET is a good example. The entity of an ASP.NET error response might contain the exception stack and its own error description. A Detailed Error is only generated if the entity body of the response is empty.

<httpErrors> Configuration

Here is the IIS custom error section obtained on a clean install:

[!code-xmlMain]

You see that if the status code of a response is 401, IIS will return a file named 401.htm.

Sub-Status Codes

Many HTTP errors have a sub-status. The IIS default Custom Errors configuration does not differentiate based sub-status codes. It sends the same Custom Error page if you enter the wrong credentials (401.1), or if you get access denied based on invalid rights to access a file (401.3). You can see the different sub-status codes in the log files or via Detailed Errors. Here is a list of the different 404 sub-status codes that IIS produces:

Status Description
404.1 Site could not be found
404.2 Denied by Policy. The request ISAPI or CGI program is not allowed in the Restriction List.
404.3 The static file handler did not have the file in its MimeMap and therefore rejected the request.
404.4 No handler was found to serve the request.
404.5 The Request Filtering Module rejected an URL sequence in the request.
404.6 The Request Filtering Module denied the HTTP verb of the request.
404.7 The Request Filtering module rejected the file extension of the request.
404.8 The Request Filtering module rejected a particular URL segment (characters between two slashes).
404.9 IIS rejected to serve a hidden file.
404.11 The Request Filtering module rejected a request that was double escaped.
404.12 The Request Filtering module rejected a request that contained high bit characters.
404.14 The Request Filtering module rejected a request with a URL that was too long.
404.15 The Request Filtering module rejected a request with a too long query string.
413.1 The Request Filtering module rejected a request that was too long (request + entity body).
431 The Request Filtering module rejected a header that was too long.

You can configure the httpErrors section to show a Custom Error for particular sub-status codes. If you add the following line to the httpErrors configuration section, IIS returns 404_3.htm if a file with a file extension is requested that is not included in the IIS MimeMap (<staticContent> configuration section).

[!code-xmlMain]

Here is how to make the example work:

  1. Add the entry above to your httpErrors configuration section.
  2. Create a file named 404_3.htm in your c:inetpubcusterren-us directory.
  3. Create a file named test.yyy in you c:inetpubwwwroot directory.
  4. Now request http://localhost/test.yyy.

The file extension .yyy is not part of the IIS MimeMap and the static file handler will not serve it.

New in IIS: Language-specific Custom Errors

Each more recent browser includes the language of the client as a request header. Here is an example of how this header might look:

[!code-consoleMain]

The syntax and registry of accepted languages is specified in RFC1766.

When generating an error, IIS takes this header into account when it looks for the custom error file it returns. It generates the path for the custom error using the following logic:

prefixLanguageFilePath configuration setting (for example c:inetpubcusterr)+
Accept-Language header sent by the client (for example en-us) +
Path configuration setting (for example 404.htm)

Example:

If the browser sends a request for an non-existing resource and the «Accept-Language» header has the value of «en-us,» the file that gets returned will be c:inetpubcusterren-us404.htm.

For example, if you are from Germany, you want your error messages in German. To do this, you must install the Windows Vista Language Pack for German. This creates the c:inetpubcusterrde-DE directory with custom error files in it. Now if the browser sends the «Accept-Language» header with the value of «de-DE, the file that gets returned will be c:inetpubcusterrde-DE404.htm.

IIS will always fall back to the system language if the directory «de-DE» does not exist.

[!NOTE]
Internet Explorer allows you to configure the Accept-Language header. Go to «Tools» — «Internet Option», select the «General» tab and click the «Languages» button.

Custom Error Options

In the above examples, IIS sends the contents of the file as the custom error response. IIS has two other ways to respond to an error: by executing an URL or by redirecting the request.

ExecuteUrl

If you want to do more in your custom error, e.g. sending an e-mail or logging the error to a database, you can execute an url. This allows you to execute dynamic content like an ASP.NET page. The example below replaces the 404 custom error. Now IIS executes /404.aspx whenever a 404 error occurs.

[!code-xmlMain]

Security Considerations

A word of caution: For architectural reasons, IIS can only execute the URL if it is located in the same Application Pool. Use the redirect feature to execute a Custom Error in a different Application Pool.

IIS can also return a 302 Redirect to the browser when a particular error occurs. Redirect is good if you have a server farm. For instance, you can redirect all your errors to a central location that you closely monitor.

There is risk however: responseMode=»File» (which is the default) allows you to specify every file on the disk. This will not work if you are very security conscious.

A workable scenario might include only allowing the delegation of the errorMode setting. This enables a developer to receive Detailed Errors for his application even if he is using a remote client. All that is necessary is to set errorMode=»Detailed». Here is how to configure this scenario:

Allow the delegation of the httpErrors section:

[!code-xmlMain]

Second, go to the <httpErrors> section in applicationHost.config and change it so that only errorMode is delegated:

[!code-xmlMain]

Summary

Custom and Detailed Errors are powerful IIS features. They help you to troubleshoot problems without compromising the security of your IIS Server. Many configuration options help you to custom tailor your users’ experience. Most importantly: experimenting with it is fun.

See also

  • Troubleshooting Common IIS Errors
title author description ms.date ms.assetid msc.legacyurl msc.type

How to Use HTTP Detailed Errors in IIS 7.0

rick-anderson

Every Web-Site Administrator or Web Developer has seen ‘404 — File not found’, ‘401 — Unauthorized’ or ‘500 — Server Error’ messages in his browser. This ar…

12/12/2007

33897393-97b8-4ee1-836f-25b1348dc3a3

/learn/troubleshoot/diagnosing-http-errors/how-to-use-http-detailed-errors-in-iis

authoredcontent

by IIS Team

Introduction

Every Web-Site Administrator or Web Developer has seen «404 — File not found», «401 — Unauthorized» or «500 — Server Error» messages in his browser. This article helps you understand how and why IIS generates these errors and how they can be configured.

Many might think that generating error messages does not seem to justify a full article. But there is more to errors than meets the eye. Error messages are a sensitive topic, because every error reveals more about your web-site than you might want revealed. The more information someone can gather about your site, the likelier it is that you will be hacked. A search for «google hacking» or «cross-site scripting» reveals a wealth of information on this topic.

However, error messages are also a valuable tool to troubleshoot problems. Developers and Web-Site Administrators require as much detail as possible when an error occurs. Ideally the error message gives recommendations on how to fix the problem. Here is how IIS addresses these fundamentally opposed goals.

Errors, What Errors?

This article talks about HTTP errors as specified in the HTTP RFC (RFC 2616 — section 6.1.1). An HTTP error is always expressed by sending a response with a status code greater than 400 back to the requesting client.

Client Errors

Status codes between 400 and 500 specify an error that the client made, e.g. bad syntax or a request to a resource that doesn’t exist. You can try this by requesting a bogus URL from the web-site of your choice, for example: http://<IIS7Server>/this_resource_does_not_exist. You get a «404 — File not found» error.

Server Errors

Status codes starting with 500 are errors caused by the server. The most common causes for 500 errors on IIS systems are:

  • An ASP or ASPX page that contains a syntax error
  • The web server configuration or the application configuration cannot be read or is invalid
  • The site is stopped

It is important to note that browsers like IE often replace errors returned from a web server with their own errors. This makes troubleshooting harder. In IE you can turn this feature off. Go to the «Tools» menu, select «Internet Options», click the «Advanced» tab and find the «Show friendly HTTP error messages» check box and uncheck it. To see the raw response, use HTTP tools like WFETCH in the IIS 6.0 Resource Kit (see «Related Links»).

HTTP Errors in IIS

There are two things that can happen when the httpError module (custerr.dll) encounters an error:

  • A custom error is generated
  • A detailed error is generated

Custom errors are error pages that the regular users of your web-site see. They contain a brief error description of why the error happened, but nothing else. Here is the custom error generated when you request a resource that does not exist, for example: http://<IIS7Server>/this_resource_does_not_exist

Screenshot of the the H T T P Error 404 file or directory not found webpage in Internet Explorer.

Detailed errors are intended for local administrators and developers. They are supposed to provide information that helps to immediately fix the problem. Here is an example of the same request, but now returning a Detailed Error:

Screenshot of the Server Error in Default Web Site Application webpage, showing a Cause and Solution section for the error.

This is dangerous, because Detailed Errors contain information about the inner workings of your web-site. Only trusted personnel should see a Detailed Error. The only way to ensures this is to only generate a detailed error if the request comes from the local machine. As soon as the request is not local, a custom error is generated. Look at the following flow diagram:

Diagram of the Status Substatus, Entity Body, and Set Error's path of creating a detailed error.

Data Flow

First: Error check

The httpError module receives a notification if a response is about to be sent (RQ_SEND_RESPONSE notification). The httpError module checks the status code of this response and immediately returns if the status code is not greater than 400.

Second: Custom Error or Detailed Error

The next check is determined by the request origin (is the request a local or remote request) and the setting of the errorMode property. The errorMode property is set to DetailedLocalOnly, which means that Custom Errors are generated for every remote request. If errorMode is set to «Custom», then all error responses will become Custom Error. If errorMode is set to «Detailed» all error responses will become Detailed Errors. The following table clarifies this behavior:

errorMode Request origin Action
DetailedLocalOnly (default) Local Detailed Error
DetailedLocalOnly (default) Remote Custom Error
Custom Local Custom Error
Custom Remote Custom Error
Detailed Local Detailed Error
Detailed Remote Detailed Error

If the httpError module determines that a Custom Error must be generated, it looks into its configuration to see if it can find a matching error. If a match is found, it sends the static file, redirects the request or executes the URL specified. If no match can be found, IIS send a basic one-line message containing the status code. The next section explains the Custom Error configuration in detail.

If custerr.dll determines that a Detailed Error must be generated, another check is needed. IIS does not touch the response if a module overrode the entity of the response with its own error description. It might contain valuable information. ASP.NET is a good example. The entity of an ASP.NET error response might contain the exception stack and its own error description. A Detailed Error is only generated if the entity body of the response is empty.

<httpErrors> Configuration

Here is the IIS custom error section obtained on a clean install:

[!code-xmlMain]

You see that if the status code of a response is 401, IIS will return a file named 401.htm.

Sub-Status Codes

Many HTTP errors have a sub-status. The IIS default Custom Errors configuration does not differentiate based sub-status codes. It sends the same Custom Error page if you enter the wrong credentials (401.1), or if you get access denied based on invalid rights to access a file (401.3). You can see the different sub-status codes in the log files or via Detailed Errors. Here is a list of the different 404 sub-status codes that IIS produces:

Status Description
404.1 Site could not be found
404.2 Denied by Policy. The request ISAPI or CGI program is not allowed in the Restriction List.
404.3 The static file handler did not have the file in its MimeMap and therefore rejected the request.
404.4 No handler was found to serve the request.
404.5 The Request Filtering Module rejected an URL sequence in the request.
404.6 The Request Filtering Module denied the HTTP verb of the request.
404.7 The Request Filtering module rejected the file extension of the request.
404.8 The Request Filtering module rejected a particular URL segment (characters between two slashes).
404.9 IIS rejected to serve a hidden file.
404.11 The Request Filtering module rejected a request that was double escaped.
404.12 The Request Filtering module rejected a request that contained high bit characters.
404.14 The Request Filtering module rejected a request with a URL that was too long.
404.15 The Request Filtering module rejected a request with a too long query string.
413.1 The Request Filtering module rejected a request that was too long (request + entity body).
431 The Request Filtering module rejected a header that was too long.

You can configure the httpErrors section to show a Custom Error for particular sub-status codes. If you add the following line to the httpErrors configuration section, IIS returns 404_3.htm if a file with a file extension is requested that is not included in the IIS MimeMap (<staticContent> configuration section).

[!code-xmlMain]

Here is how to make the example work:

  1. Add the entry above to your httpErrors configuration section.
  2. Create a file named 404_3.htm in your c:inetpubcusterren-us directory.
  3. Create a file named test.yyy in you c:inetpubwwwroot directory.
  4. Now request http://localhost/test.yyy.

The file extension .yyy is not part of the IIS MimeMap and the static file handler will not serve it.

New in IIS: Language-specific Custom Errors

Each more recent browser includes the language of the client as a request header. Here is an example of how this header might look:

[!code-consoleMain]

The syntax and registry of accepted languages is specified in RFC1766.

When generating an error, IIS takes this header into account when it looks for the custom error file it returns. It generates the path for the custom error using the following logic:

prefixLanguageFilePath configuration setting (for example c:inetpubcusterr)+
Accept-Language header sent by the client (for example en-us) +
Path configuration setting (for example 404.htm)

Example:

If the browser sends a request for an non-existing resource and the «Accept-Language» header has the value of «en-us,» the file that gets returned will be c:inetpubcusterren-us404.htm.

For example, if you are from Germany, you want your error messages in German. To do this, you must install the Windows Vista Language Pack for German. This creates the c:inetpubcusterrde-DE directory with custom error files in it. Now if the browser sends the «Accept-Language» header with the value of «de-DE, the file that gets returned will be c:inetpubcusterrde-DE404.htm.

IIS will always fall back to the system language if the directory «de-DE» does not exist.

[!NOTE]
Internet Explorer allows you to configure the Accept-Language header. Go to «Tools» — «Internet Option», select the «General» tab and click the «Languages» button.

Custom Error Options

In the above examples, IIS sends the contents of the file as the custom error response. IIS has two other ways to respond to an error: by executing an URL or by redirecting the request.

ExecuteUrl

If you want to do more in your custom error, e.g. sending an e-mail or logging the error to a database, you can execute an url. This allows you to execute dynamic content like an ASP.NET page. The example below replaces the 404 custom error. Now IIS executes /404.aspx whenever a 404 error occurs.

[!code-xmlMain]

Security Considerations

A word of caution: For architectural reasons, IIS can only execute the URL if it is located in the same Application Pool. Use the redirect feature to execute a Custom Error in a different Application Pool.

IIS can also return a 302 Redirect to the browser when a particular error occurs. Redirect is good if you have a server farm. For instance, you can redirect all your errors to a central location that you closely monitor.

There is risk however: responseMode=»File» (which is the default) allows you to specify every file on the disk. This will not work if you are very security conscious.

A workable scenario might include only allowing the delegation of the errorMode setting. This enables a developer to receive Detailed Errors for his application even if he is using a remote client. All that is necessary is to set errorMode=»Detailed». Here is how to configure this scenario:

Allow the delegation of the httpErrors section:

[!code-xmlMain]

Second, go to the <httpErrors> section in applicationHost.config and change it so that only errorMode is delegated:

[!code-xmlMain]

Summary

Custom and Detailed Errors are powerful IIS features. They help you to troubleshoot problems without compromising the security of your IIS Server. Many configuration options help you to custom tailor your users’ experience. Most importantly: experimenting with it is fun.

See also

  • Troubleshooting Common IIS Errors

Понравилась статья? Поделить с друзьями:
  • Iis код ошибки 0x8007000d
  • Imac ошибка 102
  • Ima honda insight ошибка
  • Iis как изменить 80 порт
  • Ima error communicating to tpm chip