Application Request Routing Version 2 Overview
Introduction
This section of the documentation applies to Microsoft Application Request Routing Version 2 for IIS 7 and Above.
Microsoft Application Request Routing (ARR) for IIS 7 and above is a proxy-based routing module that forwards HTTP requests to application servers based on HTTP headers, server variables, and load balance algorithms.
ARR Version 2 is an incremental release that includes all of the features from Version 1, and adds support for disk-based cache. More specifically, ARR Version 2 can be used to:
Enhance ARR Version 1 scenarios with disk cache.
Use ARR as a cache proxy as a cache node in a CDN/ECN environment.
Features
ARR Version 2 includes the following key features:
Support
ARR Version 2 is a Released to Web (RTW) product and support is provided by Microsoft Help and Support. The forum will remain active.
Get the module
Using the module
The following articles explain how to install and configure ARR Version 2. It is strongly recommended that these articles are read in the order listed below as they get progressively more advanced.
Changes in URL Rewrite Module
ARR Version 2 includes the updated version of URL Rewrite Module 2.0, which has several breaking changes that were introduced since the release of the URL Rewrite 2.0 Beta. The breaking changes are listed below:
The HTTP_CONTENT_TYPE server variable has been replaced with RESPONSE_CONTENT_TYPE. If an outbound rewrite rule uses a pre-condition that checks the HTTP_CONTENT_TYPE, then that rule will stop working. Change the pre-condition to use RESPONSE_CONTENT_TYPE instead.
Ферма IIS и Application Request Routing
Совсем недавно мои коллеги написали несколько статей про shared-хостинг на базе Cloud Linux, а сегодня я расскажу вам про технологии Microsoft которые мы используем для услуги Windows-хостинга. Речь пойдет про связку IIS 8.5 и Application Request Routing (ARR).
Как это работает у нас?
Раньше для предоставления shared-хостинга на базе Windows, мы использовали одиночные сервера. По мере их заполнения появлялись новые и новые узлы, которые не были объединены единой конфигурацией. Со временем это стало доставлять неудобства как для клиентов, так и для системных администраторов, которым приходилось обслуживать весь этот зоопарк. В качестве примера можно привести обновление ОС на веб-сервере, требующее перезагрузки, а в следовательно и приостановки работы всех сайтов, размещенных на нем.
Сейчас я расскажу вам, про минимальную отказоустойчивую конфигурацию которая используется в основе нашего shared-хостинга.
Хостингом наши клиенты управляют через личный кабинет. Все задачи, которые пользователь отправляет на выполнение ставятся в очередь и за дело берется оркестратор. Он-то и управляет всеми услугами Windows-хостинга с помощью PowerShell-сценариев.
Но бывают и особо требовательные клиенты. Нам есть что предложить и им: гео-распределенные фермы. Они физически разнесены по нескольким ЦОДам. Репликация данных происходит на уровне файловых хранилищ. Для этого отлично подходит DFS. Данные клиента между ЦОДами могут реплицироваться как в автоматическом режиме, так и по запросу. А поскольку кроме контента реплицируется и вся конфигурация веб-серверов, то это является дополнительным бонусом к снижению издержек на администрирование всего этого хозяйства.
На сегодня все, в следующей статье я постараюсь подробно описать как заставить все это жить в гармонии и бесперебойно выполнять свои обязанности.
Application Request Routing
Windows This is a Microsoft Supported Download | Works With: IIS 7, IIS 7.5, IIS 8, IIS 8.5, IIS 10
Overview
Balance loads more efficiently across servers to maximize resource utilization
IIS Application Request Routing offers administrators the ability to create powerful routing rules based on the URL, HTTP headers, and server variables to determine the most appropriate Web application server for each request. ARR makes request routing decisions at the application level, and can be used in conjunction with hardware load balancers or Windows Network Load Balancing as an added layer of control over HTTP requests. In addition, ARR enable hosting providers to route requests from clients to specific Web application servers in a server farm by creating an affinity between the client and server.
Manage and monitor multiple server farms more easily through IIS Manager
ARR lets administrators and hosting providers create, manage, and apply load balancing rules to server farms in IIS Manager. They can easily add or remove servers from a server farm to match demand throughput without impacting application availability. ARR also includes live traffic and URL test monitoring capabilities to determine the health of individual servers and configuration settings, while allowing administrators to view aggregated runtime statistics in IIS Manager.
Optimize bandwidth use and scale your server capacity through disk caching
ARR is able to cache on disk any HTTP traffic that passes through the server. By combining the disk caching capabilities along with a hierarchy of IIS Web servers running ARR, CDNs and hosting providers are able to considerably reduce the network traffic that traverses up to the origin server. This new feature makes it possible to use their primary HTTP network infrastructure to cache the content closer to the client and make the delivery more efficient, such as live and on demand video events in true HD quality (720p+) when combining the use of ARR and IIS Live Smooth Streaming.
Features
Download ARR 3.0
Installing ARR 3.0 manually
ARR depends on URL Rewrite. Ensure URL Rewrite is installed prior to installing ARR. Alternatively, use the Microsoft Web Platform Installer link instead which installs the ARR and its dependency in the right order.
Reverse Proxy with URL Rewrite v2 and Application Request Routing
This walkthrough will guide you through how to use URL Rewrite Module and Application Request Routing (ARR) to implement a reverse proxy server for multiple back-end applications.
Prerequisites
To run this walkthrough, you must have the following:
Introduction
By using URL Rewrite Module and Application Request Routing you can implement complex and flexible load balancing and reverse proxy configurations. A very common reverse proxy scenario is to make available several internal web applications over the Internet. An Internet-accessible Web server is used as a reverse-proxy server that receives Web requests and then forwards them to several intranet applications for processing: The following figure illustrates a typical configuration for a reverse-proxy scenario:
In addition, if internal application inserts links into its response HTML that link to elsewhere in those applications, those links should be modified before the response is returned to the client. For example, a page from http://webmail/default.aspx might contain a link like this:
Then ARR server should change this link to the following:
Creating the Example Web Sites
For simplicity, the reverse-proxy scenario you will work with in this walkthrough will be implemented on a single server, with the IIS «Default Web Site» acting as a reverse-proxy site and webmail and payroll applications hosted in separate IIS web sites on the same server.
To create the example Web sites:
Create two folders called «webmail» and «payroll» in the following folder:
Create a file named default.aspx in the following folder:
Copy the following ASP.NET markup, paste it into the file, and save the file:
Create a file named default.aspx in the following folder:
Copy the following ASP.NET markup, paste it into the file, and save the file:
To make sure that sites are working correctly, open a Web browse and request the following URLs:
Configuring Rules for the Reverse Proxy
In this section of the walkthrough, you will configure reverse proxy functionality to work with the example Web sites that you have created.
Enabling Reverse Proxy functionality
Reverse Proxy functionality is disabled by default, so you must begin by enabling it.
Creating a rule for webmail application
You will create two rewrite rules:
To add the reverse proxy rewrite rules:
Open the web.config file located in the following location:
Under the /configuration/system.webServer element, add the following and then save the file:
For more information about creating rewrite rules, see Creating Rewrite Rules for the URL Rewrite Module.
Testing the reverse proxy functionality
Configuring rules for response rewriting
This section of the documentation applies to the URL Rewrite Module Version 2.0 for IIS 7.
You will define an outbound rule that replaces all the links within the response HTML as follows:
will be replaced with:
(if the response came from webmail application)
(if the response came from payroll application)
When response headers or the response content is modified by an outbound rewrite rule an extra caution should be taken to ensure that the text which gets inserted into the response does not contain any client side executable code, which can result in cross-site scripting vulnerabilities. This is especially important when rewrite rule uses un-trusted data, such as HTTP headers or the query string, to build the string that will be inserted into the HTTP response. In such cases the replacement string should be HTML encoded by using the HtmlEncode function, e.g:
To create the rule, follow these steps:
Now you must define the actual outbound rule. In the URL Rewrite Module 2.0, an outbound rewrite rule is defined by specifying the following information:
Naming the rule
In the «Name» text box enter a name that will uniquely identify the rule, for example: «Add application prefix».
Defining a Precondition
A precondition is used to evaluate whether the outbound rules evaluation should be performed on a response. For example if a rule that modifies HTML content, only HTTP responses with content-type header set to «text/html» should be evaluated against this rule. Outbound rules evaluation and content rewriting is a CPU intensive operation that may negatively affect the performance of a web application. Therefore, use preconditions to narrow down the cases when outbound rules are applied.
Because the rule that you are creating should be applied only on HTML responses, you will define a precondition that checks whether the HTTP response header content-type is equial to «text/html».
To define a precondition:
In the Pre-conditions list, select » «.
This will bring you to the Pre-condition editor dialog, where you will need to define the precondition. Specify the precondition settings as follows:
Using: «Regular Expressions«
Click «Add» to bring up the «Add condition» dialog. In this dialog specify:
Condition input: » «
Check if input string: «Matches the pattern«
Pattern: «^text/html«
Click OK to save the precondition and to return to the «Edit Rule» page.
Defining a matching scope
The outbound rewrite rule can operate on the content of an HTTP header or on the response body content. This rule needs to replace links in the response content so in the «Matching Scope» drop down list choose «Response«.
Defining a tag filter
Tag filters are used to scope the pattern matching to a certain HTML elements only, instead of evaluating the entire response against the rule’s pattern. Pattern matching is a very CPU-intensive operation and if an entire response is evaluated against a pattern, it can significantly slow down the Web application response time. Tag filters allow you to specify that the pattern matching should be applied only within the content of certain HTML tags, thus significantly reducing the amount of data that has to be evaluated against regular expression pattern.
To define a tag filter, expand the drop down list «Match the content within: » and then select and check the check box «A (href attribute)«.
This sets the rule to apply the pattern only to the value of the href attribute of the hyperlink, as in the following example:
Defining a pattern
In the «Pattern» text box enter the following string:
This string is a regular expression that specifies that the pattern will match any URL path string that starts with «/» symbol.
Note the usage of parenthesis within the pattern. These parentheses create a capture group, which can be later referenced in the rule by using back-references.
Defining a condition
You need to change the links in the response HTML only if response is from the webmail or payroll application. To check that you will use a condition that analyzes the URL path requested by client. Also you will define a condition pattern that captures the application folder from the requested URL, so that rule could re-use that when rewriting the links in the response.
Defining an action
Choose the «Rewrite» action type that is listed in the «Action» group box. In the «Value» text box, enter the following string:
This string specifies the new value to which the link address should be rewritten. The
Leave default values for all other settings. The «Edit Outbound Rule» property page should look like below:
Save the rule by clicking on «Apply» action on the right hand side.
Testing the rule
Summary
In this walkthrough you have learned how to configure URL Rewrite Module and Application Request Routing to implement a reverse proxy scenario. Also you have learned how to use new outbound rewriting feature of URL Rewrite Module 2.0 to fix up the links in the applications’ responses before serving them to web client.
Note that when using reverse proxy it often is also required to rewrite the HTTP response headers. To learn how to use URL Rewrite Module 2.0 to modify the response HTTP header refer to Modifying HTTP Response Headers.
Reverse Proxy на базе IIS
Данный пост появился в результате демонстрации, проведённой для меня Александром Станкевичем. О возможности организовать Reverse Proxy-сервер на базе IIS я до этого не знал. В стандартном комплекте IIS этой возможности нет — нужно установить специальный компонент IIS, который называется Application Request Routing.
После установки ARR в окне просмотра функций нашего IIS сервера (в оснастке Internet Information Services Manager) появится «URL Rewrite», а в дереве сайтов — пункт «Server Farms»:
На базе модуля «URL Rewrite» и можно построить Reverse Proxy-сервер. Важно помнить, что «URL Rewrite» доступен как на уровне всего сервера, так и на уровне отдельных сайтов и приложений, расположенных в этих сайтах. Поэтому Reverse Proxy на базе IIS сервера можно очень гибко настраивать.
Фермы
Для начала имеет смысл создать ферму серверов, которые будут получателями трафика, пересылаемого Reverse Proxy-сервером:
Затем надо будет указать имя фермы и добавить имена серверов. Из интересного — в дополнительных настройках серверов можно указать какие порты будут слушать HTTP/HTTPS-трафик, а так же вес сервера:
Последним шагом будет предложено создать правило, которое будет перенаправлять весь входящий трафик на новую ферму. Имеет смысл с этим согласиться.
Бонусов в создании фермы достаточно много. Для фермы мы можем включить кэширование, настроить проверку доступности нашего Web-сервера, балансировку (доступно большое количество условий, по которым можно выполнять балансировку) и т. д. Полный набор доступных функций ниже:
Правила
По завершении создания фермы можно посмотреть на только что созданное правило. Оно будет находиться на уровне сервера IIS в «URL Rewrite» и называться «ARR_FarmName_loadbalance». Правило пересылает все запросы, приходящие на сервер IIS и подходящие под шаблон «*», на нашу новую ферму и по завершении останавливает выполнение других правил:
Остановимся подробнее на правилах. Правила состоят из четырёх компонентов:
Запросы, проходящие через наш Reverse Proxy-сервер, содержат URL сервера, к которому обращается клиент. В общем случае он выглядит следующим образом:
Match URL работает с
и доступны в Conditions через переменные «HTTP_HOST», «SERVER_PORT» и «QUERY_STRING». Так же в Conditions доступны переменные «SERVER_PORT_SECURE» и «HTTPS» для обработки HTTP-запросов.
Подробнее о компонентах.
Match URL
Для фильтрации используются шаблоны на основе регулярных выражений или подстановочных знаков (wildcards). Можно делать инвертированные правила (которые обрабатывают все запросы, не удовлетворяющие данному шаблону). Так же есть возможность включить/выключить игнорирование строчных и прописных букв в запросе.
Conditions
Для использования дополнительных условий фильтрации доступны переменные, указанные выше. Можно требовать одновременного выполнения всех условий, либо любого условия из списка (Match All или Match Any). Например, на картинке ниже, мы указали, чтобы в фильтр попадали все запросы, в которых содержится URL с доменным именем «cwapp.domain.com» и доступ осуществлялся по HTTPS:
Помимо стандартных переменных, список которых я указал выше, можно использовать любые переменные, находящиеся в HTTP-запросе, который проходит через Reverese Proxy. Имя такой новой переменной собирается следующим образом:
Прекрасным примером использования переменных может служить правило, созданное на сервере переднего плана Lync, для мобильных клиентов:
Action
В Action указывается действие, которому подвергается HTTP-запрос, удовлетворяющий Match URL и Conditions. Доступны следующие действия:
Возвращаемся к Reverse Proxy. Предположим, нам необходимо перенаправлять запросы, идущие к «http://cwapp.domain.com», на сервер переднего плана Lync. Для этого укажем по какому IP-адресу будет отвечать наш сайт, отвечающий за Reverse Proxy. В DNS необходимо будет прописать хост «cwapp.domain.com» с IP-адресом, который мы закрепили за Web-сайтом. Затем, на уровне сайта заходим в URL Rewrite и добавляем правило (Add Rule(s)…), указываем тип правила — «Reverse Proxy»:
Затем вводим, на какой сервер перенаправлять запросы:
В итоге получаем простейшее правило, которое будет перенаправлять запросы, приходящие к нашему сайту, на сервер переднего плана Lync (или на любой другой, который укажем).
Используя новые знания, можно попробовать настроить более хитрое обратное Proxy’рование запросов, приходящих на наш сайт IIS (и не только на него).
Попробуем настроить перенаправление клиентских запросов к «https://meet.domain.com». Для этого на уровне сервера IIS заходим в «URL Rewrite» и создаём новое правило:
Далее нужно будет указать название для правила, а так же шаблон для запросов, попадающих под его действие (можно использовать подстановку «*»):
В дополнительных условиях указываем имя хоста (meet.domain.com) и использование в запросе HTTPS-протокола:
В действиях правила указываем перенаправлять запрос на ферму серверов Lync по HTTPS. Не забываем включить настройку отключения выполнения других правил:
Таким образом, решение на базе сервера IIS и дополнительного компонента «Application Request Routing» вполне может заменить, в некоторых случаях, более тяжёлые решения на базе «Microsoft Threat Management Gateway» или аппаратных балансировщиков нагрузки.
Особая благодарность выражается Александру Станкевичу за помощь в написании данной статьи. Если вас заинтересовала данная тема, можете посмотреть его видео-демонстрацию по установке и настройке «Application Request Routing» в контексте использования для «Lync Mobility».























