Iis обработка ошибок

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

По умолчанию, «используемый по умолчанию веб-узел» и все его приложения передают обработку ошибок ASP файлу 500-100.asp; однако, любой новый создаваемый пользователем веб-узел, или его приложения, будут передавать обработку ошибок 500;100 стандартному, а не специальному файлу ошибок. Если нужно предусмотреть дополнительную обработку ошибок .asp-файлов, это можно сделать либо путем отображения ошибки 500-100 на файл 500-100.asp, либо путем создания собственного .asp-файла обработки ошибок.

Файл 500-100.asp обрабатывает все ошибки, возникающие при компиляции или запуске .asp-файлов. При возникновении ошибки ASP IIS возвращает файл 500-100.asp, содержащий подробные сведения об ошибке, например номер строки, которая вызвала ошибку, и описание ошибки.

При создании собственного файла обработки ошибок ASP нужно будет разрешить его использование в оснастке Internet Information Services. Дополнительные сведения см. в разделе Добавление специального сообщения об ошибке.

Сведения о том, как использовать для обработки ошибок ASP объект ASPError, см. в разделе Объект ASPError.

Примечания

  • Если файл 500-100.asp сам содержит ошибки ASP, то ASP не будет возвращать еще один файл 500-100.asp; вместо этого об ошибке будет сообщено так, как если бы для ошибок 500-100 вообще не было создано специального файла.
  • Если файл обработки ошибок (по умолчанию это файл 500-100.asp) содержит ошибку времени выполнения, то будет сообщено только об этой ошибке, независимо от типа ошибки в запрошенном ASP-файле. Если файл обработки ошибок содержит ошибки, выявляемые при предобработке или компиляции, то в обозревателе будут отображены обе ошибки (ошибка из файла 500-100.asp и ошибка из запрошенного ASP-файла).

Сегодня обсудим, как на asp.net mvc можно настроить обработку ошибок 404, 500, ну и любых других. Рассмотрим на примере 404 и 500, как наиболее популярных и важных. Как вместо стандартного не очень красивого желтого окна ошибки показывать свои собственные красивые интересные страницы, и при этом как правильно отдавать код ошибки в браузер пользователя.

Казалось бы, задача довольно тривиальная и может быть решена написанием буквально пары строк кода. Действительно, так и есть, если вы используете любую популярную серверную технологию. Но только не ASP.NET. Если ваше приложение написано на ASP.NET MVC, и вы первый раз сталкиваетесь с проблемой обработки ошибок, очень легко запутаться и сделать неправильные настройки. Что впоследствии негативно отразится на продвижении сайта в поисковых системах, удобстве работы для пользователя, SEO-оптимизации.

Рассмотрим два подхода, как настроить страницы ошибок. Они в целом похожи, какой выбрать – решать вам.

Для начала вспомним, что означают наиболее популярные коды ошибок, которые отдает сервер.

Код ответа 200. Это значит что все ОК. Запрос клиента обработан успешно, и сервер отдал затребованные клиентом данные в полном объеме. Например, пользователь кликнул по гиперссылке, и в ответ на это в браузере отобразилась нужная ему информация.

Код ответа 404. Это означает, что запрошенный клиентом ресурс не найден на сервере. Например, указанная в адресе гиперссылки статья не найдена, или *.pdf файл был удален и теперь недоступен для скачивания.

Код ответа 500. Внутренняя ошибка на сайте. Что-то сломалось. Это может быть все что угодно, от неправильно написанного кода программистом, до отказа оборудования на сервере.

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

Стандартная страница ошибки

Стандартная страница ошибки

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

Вариант 1. Ссылка на статичные заранее подготовленные html-страницы.

Первым делом в файле web.config в разделе system.web добавляем новую секцию customErrors со следующими настройками:

web.config

<system.web>
  <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/404.aspx">
    <error statusCode="404" redirect="~/404.aspx"/>
    <error statusCode="500" redirect="~/500.aspx"/>
  </customErrors>
  ...
</system.web>

Эта секция служит для обработки ошибок на уровне платформы ASP.NET.

Атрибут mode=»On» определяет, что пользовательские страницы ошибок включены. Также допустимы значения Off / RemoteOnly.

Атрибут redirectMode=»ResponseRewrite» определяет, следует ли изменять URL-адрес запроса при перенаправлении на пользовательскую страницу ошибки. Естественно, нам этого не нужно.

Атрибут defaultRedirect=»~/404.aspx» указывает на то, какая страница ошибки будет показана в случае возникновения кода ответа сервера, который мы не описали в настройках. Пусть при любых других ошибках пользователь будет думать, что страница не найдена.

И уже внутри этой секции мы определяем два кода, для которых у нас будут кастомные страницы ошибок.

Далее, как видно из настроек выше, нам понадобятся *.aspx файлы, на которые будет делаться редирект. Обратите внимание, что мы ссылаемся именно на *.aspx файлы, а не на *.html. Эти файлы являются проходными, служебными, в них содержатся настройки для ответа сервера. Содержимое файла 404.aspx:

404.aspx

<%@ Page Language="C#" %>

<%
    var filePath = MapPath("~/404.html");
    Response.StatusCode = 404;
    Response.ContentType = "text/html; charset=utf-8";
    Response.WriteFile(filePath);
%>

В коде выше мы указываем путь непосредственно до конечного *.html файла, а также дополняем настройки ответа сервера. Указываем код ответа, тип отдаваемого контента и кодировку. Если не указать кодировку, то браузер пользователя может интерпретировать ответ от сервера как не отформатированную строку, и, соответственно, не преобразует ее в html-разметку. А если не указать StatusCode = 404 , то получится следующая интересная ситуация:

Код ответа сервера отдается неверно

Код ответа сервера отдается неверно

И хотя на рисунке выше нам показывается пользовательская страница с ошибкой, при этом код ответа 200 — это конечно же неверно. Когда-то давно на форумах Microsoft такое поведение зарепортили как баг. Однако Microsoft возразила, что это не баг, а фича и не стала ничего менять в будущих релизах ASP.NET. Поэтому приходится это исправлять вручную, и вручную в *.aspx файле в ответе сервера указывать код ответа 404.

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

Также по аналогии создаем подобный *.aspx файл для ошибки 500.

И уже после этого нам нужно создать статичные html-файлы, соответственно для ошибок 404 и 500. Пусть они лежат в корне нашего проекта.

Статичные файлы расположены в корне проекта

Статичные файлы расположены в корне проекта

Здесь же в файле web.config определяем раздел system.WebServer, если он еще не определен, и в нем объявляем секцию httpErrors:

web.config

  <system.webServer>
    <httpErrors errorMode="Custom" defaultResponseMode="File" defaultPath="c:projectsmysite404.html">
      <remove statusCode="404" />
      <remove statusCode="500" />
      <error statusCode="404" path="404.html" responseMode="File" />
      <error statusCode="500" path="500.html" responseMode="File" />
    </httpErrors>
  </system.webServer>

Эта секция служит для обработки ошибок на уровне сервера IIS. Суть в том, что иногда обработка запроса происходит непосредственно на уровне ASP.NET. А иногда ASP.NET просто определяет нужный код ответа и пропускает запрос выше, на уровень сервера. Такой сценарий может случиться, если, например, мы в действии контроллера возвращаем экземпляр класса HttpNotFound:

Или же когда система маршрутизации в MVC-приложении не может определить, к какому маршруту отнести запрошенный пользователем URL-адрес:

https://site.com/long/long/long/long/path

Для секции httpErrors важно отметить следующее. Так как мы ссылаемся на статичные *.html файлы, то и в качестве значений для нужных атрибутов здесь также указываем File . Для атрибута defaultPath необходимо указать абсолютный путь до файла ошибки. Относительный путь именно в этом месте работать не будет. Сам атрибут defaultPath определяет файл, который будет выбран для всех других ошибок, которые мы явно не указали. Но здесь есть одна небольшая проблема. Дело в том, что этот атрибут по умолчанию заблокирован на сервере IIS Express. Если вы разрабатываете свое приложение именно на локальном сервере, то это ограничение нужно снять. Для этого в директории своего проекта нужно найти файл конфигурации сервера и удалить этот атрибут из заблокированных, как это показано на рисунке:

Расположение файла applicationhost.config

Расположение файла applicationhost.config

Также проверьте папку App_Start. Если вы создали не пустое приложение, а работаете над реальным проектом, там может находиться класс FilterConfig, в котором регистрируются все глобальные фильтры в приложении. В методе регистрации удалите строчку кода, где регистрируется HandleErrorAttribute, в нашем случае он не понадобится.

Вот такой комплекс мер нужно предпринять, чтобы настроить обработку ошибок 404, 500, и любых других. Это настройки в файле web.config, и добавление в наш проект статичных файлов.

Вариант 2. Обработка ошибок с использованием специального контроллера.

Второй подход немного отличается от первого. Здесь нам не понадобится секция customErrors, так как обработку всех ошибок мы будем передавать сразу из приложения на уровень сервера, и он уже будет решать что делать. Можно удалить или закомментировать эту секцию в файле web.config.

Далее создадим специальный контроллер, который будет принимать все ошибки, которые мы хотим обрабатывать:

public class ErrorController : Controller
{
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;
        return View();
    }

    public ActionResult Internal()
    {
        Response.StatusCode = 500;
        return View();
    }
}

Также создадим соответствующие представления с нужной нам красивой разметкой.

Также в файле web.config нам нужно изменить настройки в секции httpErrors. Если раньше мы ссылались на статичные html-файлы, то теперь мы будем обращаться по указанным URL, которые мы определили в ErrorController’е, чтобы именно там обрабатывать ошибки:

web.config

<httpErrors errorMode="Custom" existingResponse="Replace" defaultResponseMode="ExecuteURL" defaultPath="/Error/NotFound">
  <remove statusCode="404"/>
  <remove statusCode="500"/>
  <error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL"/>
  <error statusCode="500" path="/Error/Internal" responseMode="ExecuteURL"/>
</httpErrors>

Вариант 3. Фильтр HandleErrorAttribute

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

Итого

Мы посмотрели на два разных подхода, которые можно применить при обработке ошибок на платформе ASP.NET. Опять же повторюсь, что если для вас не принципиально настраивать собственные страницы ошибок, то лучше не изменять эти настройки, так как даже одна упущенная деталь или неверно сконфигурированный параметр может очень сильно навредить репутации вашего сайта для конечного пользователя и в поисковых системах.

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

  1. Why are detailed errors important?
  2. Enabling detailed errors using the IIS manager
  3. 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 penetration testing. He loves writing for his blog.

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

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

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:

  1. Open the IIS manager by pressing WinKey+R, typing inetmgr, and pressing Enter.
  2. Expand the Sites node and select the website for which you want to enable detailed errors.
  3. 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

Locating the error pages section in the IIS manager

  1. In the Actions pane on the right, click Edit Feature Settings.

Enabling detailed errors in IIS manager

Enabling detailed errors in IIS manager

  1. In Error Responses, you will see three options:
    1. Custom error pages
    2. Detailed errors
    3. Detailed errors for local requests and custom error pages for remote requests (default)
  2. Now select either the second or third option and click OK.

Viewing the detailed error modes in IIS

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

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.

Skip to content

IIS — Перенаправить ошибку 404 на страницу

Home/Iis/IIS — Перенаправить ошибку 404 на страницу

IIS — Перенаправить ошибку 404 на страницу

Хотите узнать, как перенаправить ошибку 404 на определенный URL на сервере IIS? В этом учебнике мы собираемся настроить сервер IIS, чтобы перенаправить ошибку 404 на конкретную страницу.

• Windows 2012 R2
• Windows 2016
• Windows 2019

Список оборудования

В следующем разделе представлен список оборудования, используемого для создания этого учебника.

Как Amazon Associate, я зарабатываю от квалификационных покупок.

Windows Учебник:

На этой странице мы предлагаем быстрый доступ к списку учебников для Windows.

Учебник IIS — Перенаправить ошибку 404 на страницу

Запустите приложение под названием: IIS Manager.

Start IIS Windows

В приложении IIS Manager выберите свой веб-сайт.

В правой части экрана доступ к опции под названием: Страницы ошибок.

IIS - Error pages

Выберите нужный номер ошибки и нажмите на опцию Редактировать.

IIS - Redirect error page

Чтобы перенаправить страницу ошибки, выполните следующую конфигурацию:

• Ответ с запросом 302 — Да.
• Абсолютный URL — Введите новый URL назначения.

Нажмите на кнопку OK.

IIS - Redirect error 404 URL

В нашем примере сервер IIS перенаправит ошибку 404 на определенный URL.

Чтобы протестировать установку, откройте браузер Chrome на удаленном компьютере и попробуйте получить доступ к странице, которая не существует.

В нашем примере в браузер был введен следующий URL::

— http://18.237.128.221/aaabbbccc

Используйте функцию проверки страницы браузера Chrome для проверки заготовок IIS.

IIS - Redirect error to URL

По желанию, вы можете использовать команду CURL компьютера Linux для тестирования конфигурации заголовка.

Поздравляю! Вы перенаправили ошибку 404 на URL на сервере IIS.

VirtualCoin CISSP, PMP, CCNP, MCSE, LPIC22021-01-31T20:35:08-03:00

Related Posts

Page load link

This website uses cookies and third party services.

Ok

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Imax b6 mini ошибки
  • Imap ошибка 550
  • Imap yandex ru ошибка при проверке
  • Imap gmail com на айфоне ошибка сертификата

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии