iis redirect to another url
Перенаправление с помощью IIS URL Rewrite
Задача: необходимо настроить перенаправление домена с префиксом www на домен без www или наоборот.
Среда:
Windows Server 2008, IIS 7.5, URL Rewrite 2.0
Решение:
Url Rewrite — расширение для IIS, с помощью которого можно создавать перенаправления и обрабатывать запросы по схожему принципу работы RewriteRules в Linux.
Итак, для того, чтобы создать перенаправление с http://www.site.com на site.com Вам необходимо выполнить такие действия :
1) Откройте IIS Manager, выберите домен и перейдите в меню «URL Rewrite»
3) Настройте перенаправление.
В появившемся меню необходимо назвать перенаправление, которое будет выделятся среди остальных. Например, url rewrite.
В выпадающем списке с названием «Using» можно выбрать тип перенаправления — wildcard (предпочтительно) или регулярное (regular).
В поле «»Pattern» (шаблон) необходимо указать *. Это обозначает применения перенаправления для всех определений.
Откройте меню “Conditions” и нажмите “Add”. В меню диалога укажите следующие параметры :
Condition input:
Check if input string: Matches the Pattern
Pattern:
Ignore case: Отмечено.
После вышеуказанных действий, нажмите «Ок». Выражения, которые будут обрабатываться, мы настроили. теперь необходимо указать действие, которое будет применяться для данных выражений. В меню «Action» укажите тип действия — Redirect (перенаправление).
Action Properties — укажите http://www.site.com/
Пункт «Append query string» должен быть отмечен. Тип перенаправления (“Redirect Type”) должен быть 301 (Permanent).
Примените данное правило, нажав кнопку «Apply». Созданное правило должно работать корректно.
HTTP Redirects
The element configures settings for Internet Information Services (IIS) 7 that redirect client requests to a new location.
There are several reasons why you might want to redirect clients to a new location. For example, if your company is migrating to a new Web site, you could redirect all requests from the old Web site to the new Web site. Likewise, if you have deployed a new application on a Web server, you could redirect all requests for the old application’s URL namespace (for example, http://www.contoso.com/app_v1.0/ ) to the new applications location (for example, http://www.contoso.com/app_v2.0/ ).
In the simplest configuration, you need only set the enabled and destination attributes of the element in order to redirect clients to a new location. However, additional elements like the exactDestination and httpResponseStatus attributes allow you to configure the end-user experience of the redirection by respectively specifying whether IIS 7 will return the destination URL exactly as entered and which HTTP response code to return to the Web client.
Compatibility
Version | Notes |
---|---|
IIS 10.0 | An additional HTTP response status was added to the element in IIS 10.0. |
IIS 8.5 | The element was not modified in IIS 8.5. |
IIS 8.0 | The element was not modified in IIS 8.0. |
IIS 7.5 | The element was not modified in IIS 7.5. |
IIS 7.0 | The element was introduced in IIS 7.0. |
IIS 6.0 | The element replaces the IIS 6.0 HttpRedirect metabase property. |
Setup
HTTP Redirection is not available on the default installation of IIS 7 and later. To install it, use the following steps.
Windows Server 2012 or Windows Server 2012 R2
Windows 8 or Windows 8.1
Windows Server 2008 or Windows Server 2008 R2
Windows Vista or Windows 7
How To
There is no user interface for adding wildcard HTTP redirects for IIS 7. For examples of how to add elements to the element programmatically, see the Code Samples section of this document.
How to add an HTTP redirect rule to a Web site or application
Open Internet Information Services (IIS) Manager:
If you are using Windows Server 2012 or Windows Server 2012 R2:
If you are using Windows 8 or Windows 8.1:
If you are using Windows Server 2008 or Windows Server 2008 R2:
If you are using Windows Vista or Windows 7:
In the Connections pane, expand the server name, expand Sites, and then navigate to the Web site or application that you want to configure custom error pages for.
In the Home pane, double-click HTTP Redirect.
In the HTTP Redirect pane, check the box to redirect requests and enter the destination URL.
You can optionally specify any of the following options:
Configure the redirection destination to be the exact destination as entered.
Configure the redirection destination to be limited to the destination URL’s root folder, not subfolders.
Configure the HTTP status code, which can be one of these three options:
IIS 7 will respectively return the following actual HTTP response statuses for each of the above options:
When you have finished all the above changes, click Apply in the Tasks pane.
Configuration
Attributes
Attribute | Description |
---|---|
childOnly | Optional Boolean attribute. |
Specifies a URL or virtual path to which to redirect the client.
Specifies whether redirection is enabled (true) or disabled (false).
Specifies that the destination value should be considered an absolute target location, not a relative location.
Specifies type of redirection.
Child Elements
Element | Description |
---|---|
add | Optional element. |
Adds a wildcard redirection rule to the collection of redirection rules.
Removes all references to wildcard redirection rules from the collection of redirection rules.
Removes a reference to a wildcard redirection rule from the collection of redirection rules.
Configuration Sample
The following default element is configured in the root ApplicationHost.config file in IIS 7 when the HTTP Redirection role service is installed. This configuration section inherits the default configuration settings unless you use the element.
The following configuration sample enables redirection and configures the destination URL to which clients are redirected.
The following configuration sample adds a wildcard redirection entry that redirects all requests for PHP files to the home page of your Web site.
This example is useful if you have removed all ASP-based applications from your Web site and you wanted client requests for the old applications to be redirected to the root of your Web site rather than receiving an HTTP 404 Not Found response.
Sample Code
The following code samples configure the Default Web Site to redirect all requests to http://www.contoso.com using an HTTP 302 status code.
AppCmd.exe
VB.NET
JavaScript
VBScript
The following code samples adds a wildcard redirection entry that redirects all requests for ASP files to the home page of your Web site.
This example is useful if you have removed all ASP-based applications from your Web site and you wanted client requests for the old applications to be redirected to the root of your Web site rather than receiving an HTTP 404 Not Found response.
Creating Rewrite Rules for the URL Rewrite Module
The URL rewrite module is an extension to IIS which is available as a download for your stand-alone IIS Server, and is also pre-installed on any website on Windows Azure Web Sites (WAWS) and available for your use. This walkthrough will guide you through how to create and test a set of rewrite rules for the URL Rewrite Module.
Prerequisites
This walkthrough requires the following prerequisites:
Setting up a test Web page
To demonstrate how the URL Rewrite Module works, we will use a simple test ASP.NET page. This page reads the Web server variables and outputs their values in the browser.
Copy the following ASP.NET code and put it in the %SystemDrive%\inetpub\wwwroot\ folder in a file called article.aspx:
After copying this file, browse to http://localhost/article.aspx and check that the page was rendered correctly in a browser.
Creating a rewrite rule
We will create a simple rewrite rule that will rewrite URLs using the following format:
We will create a rewrite rule by using URL Rewrite UI in IIS Manager. To do this, follow these steps:
Now you must define the actual rewrite rule. In the URL Rewrite Module, a rewrite rule is defined by specifying four required pieces of information:
Naming a rule
In the Name text box, enter a name that will uniquely identify the rule, for example: «Rewrite to article.aspx».
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 string that meets the following conditions:
Notice that certain parts of the regular expression are within parentheses. These parentheses create capture groups, which can be later referenced in the rule by using back-references.
Defining an action
Since the rule that we are creating is supposed to rewrite the URL, choose the Rewrite action type that is listed in the Action group box. In the Rewrite URL: text box, enter the following string:
This string specifies the new value to which the input URL should be rewritten. Notice that for the values of the query string parameters we used
Leave default values for all other settings. The Edit Inbound Rule property page should look like the following page:
Save the rule by clicking Apply on the right-hand side.
Viewing the rewrite rule in configuration file
The rewrite rules are stored either in the ApplicationHost.config file or in Web.config files. To check the configuration of the rule that we have just created, open a Web.config file located in %SystemDrive%\inetpub\wwwroot. In this file you should see the section that contains this rule definition:
The syntax above also applies to configuring URL Rewrite in Web.config in Windows Azure Web Sites (WAWS).
Testing the rewrite rule
To test that the rule correctly rewrites URLs, open a Web browser and request the following URL:
You should see that the rewrite rule on your Web server has changed the original URL to Article.aspx and it has passed «234» and «some-title» as values for query string parameters.
Creating a redirect rule
Now we will create a redirect rule that will redirect all URLs in the following format:
http://localhost/blog/some-other-title/543
to the following format:
http://localhost/article/543/some-other-title
A redirect rule enables more than one URL to point to a single Web page.
To do this, open the URL Rewrite feature view UI in IIS Manager. Click Add Rule(s)…, and then select the Blank Rule template again.
Within the Edit Rule page, enter the following:
Enter the name, pattern, and action as shown below:
Enter the redirect URL as shown below:
Leave default values for all other settings. Save the rule by clicking Apply on the right-hand side.
Testing the redirect rule
To test that the rule redirects requests correctly, open a Web browser and request the following URL:
You should see that the browser was redirected to http://localhost/article/323/some-other-title as a result of redirect rule execution and then the request was rewritten in accordance with the rewrite rule that you have created earlier.
Creating an access block rule
The third rule that we will create is used to block all requests made to a Web site if those requests do not have the host header set. This type of rule is useful when you want to prevent hacking attempts that are made by issuing HTTP requests against the IP address of the server instead of using the host name.
We will create this rule without using IIS Manager. Open the Web.config file in the %SystemDrive%\inetpub\wwwroot\ folder that you used for the article.aspx test file early in this article. Locate the section. Insert the following rule into the collection, so that it is the first rule in the collection:
The section should look like the following code:
Let’s analyze the rule to understand what it does.
The element above says that the rule will match any URL string.
The element above adds a condition to the rule that retrieves the host header value by reading the server variable HTTP_HOST, matches it against the pattern «localhost» and then negates the result of matching. In other words, the condition verifies that the host header does not match «localhost».
The element above tells the URL Rewrite Module to end the HTTP request.
Testing the access block rule
The unsuccessful display will be the following:
The successful display will be the following:
URL Rewrite Module Configuration Reference
This article provides an overview of the URL Rewrite Module and explains the configuration concepts that are used by the module.
Functionality Overview
The URL Rewrite Module rewrites request URLs to simple, user-friendly, and search-engine friendly addresses that are displayed to users or in Web applications. URL Rewrite uses defined rules to evaluate and then map the request URL to the address defined in the rule before it is processed by an IIS Web server. You can define URL rewriting logic that includes regular expressions and wildcards, and rules can be applied based on the request URL, HTTP headers, and server variables. While the primary purpose of the module is to rewrite request URLs to more friendly URLs, you can also use the module to define rules that perform redirects, send custom responses, or abort requests.
Rewrite Rules Overview
A rewrite rule defines the logic of what to compare or match the request URL with, and what to do if the comparison is successful.
Rewrite rules consists of the following parts:
Rewrite Rules Scope
Rewrite rules can be defined in two different collections:
Rules Evaluation
Each configuration level in IIS can have zero or more rewrite rules defined. The rules are evaluated in the same order in which they are specified. The URL Rewrite Module processes the set of rules by using the following algorithm:
A rule may have the StopProcessing flag turned on. When the rule action is performed (i.e. the rule matched) and this flag is turned on, it means that no more subsequent rules will be processed and the request will be passed to the IIS request pipeline. By default, this flag is turned off.
Rules Inheritance
If rules are defined on multiple configuration levels, the URL Rewrite Module evaluates the rules in the following order:
Preserving Original URL
The URL Rewrite Module preserves the original requested URL path in the following server variables:
Accessing URL Parts from a Rewrite Rule
It is important to understand how certain parts of the URL string can be accessed from a rewrite rule.
For an HTTP URL in this form: http(s):// :
Rewrite Rule Configuration
Rule Pattern
A rewrite rule pattern is used to specify a pattern to which the current URL path is compared. Current, in this context, means the value of the URL path when the rule is applied. If there were any rules that preceded the current rule, they may have matched the original requested URL and modified it. The URL string that is evaluated against the pattern does not include the query string. To include the query string in the rule evaluation you can use the QUERY_STRING server variable in the rule’s condition. For more information, refer to «Using server variables in rewrite rules».
A pattern is specified within a element of a rewrite rule.
Rule pattern syntax
Rule pattern syntax can be specified by using the patternSyntax attribute of a rule. This attribute can be set to one of the following options:
ECMAScript – Perl compatible (ECMAScript standard compliant) regular expression syntax. This is a default option for any rule. This is an example of the pattern format: «^([_0-9a-zA-Z-]+/)?(wp-.*)»
Wildcard – Wildcard syntax used in IIS HTTP redirection module. The following is an example of a pattern in this format: «/Scripts/*_in. «, where asterisk («*») means «match any number of any characters and capture them in a back-reference» and «?» means match exactly one character (no back-reference is created).
The scope of the patternSyntax attribute is per rule, meaning that it applies to the current rule’s pattern and to all patterns used within conditions of that rule.
Rule pattern properties
A pattern can be negated by using the negate attribute of the element. When this attribute is used, the rule action is performed only if the current URL does not match the specified pattern.
By default, case-insensitive pattern matching is used. To enable case sensitivity, you can use the ignoreCase attribute of the element of the rule.
Rule conditions
Rule conditions allow defining additional logic for rule evaluation, which can be based on inputs other than just a current URL string. Any rule can have zero or more conditions. Rule conditions are evaluated after the rule pattern match is successful.
Conditions are defined within a collection of a rewrite rule. This collection has an attribute called logicalGrouping that controls how conditions are evaluated. If a rule has conditions, then the rule action is performed only if rule pattern is matched and:
A condition is defined by specifying the following properties:
Condition input specifies which item to use as an input for the condition evaluation. Condition input is an arbitrary string that can include server variables and back-references to prior condition patterns and/or to rule patterns.
The match type can be one of the following three options:
IsFile – This match type is used to determine whether the input string contains a physical path to a file on a file system. If a condition input string is not specified, the URL Rewrite Module uses the physical path of the requested file as a default value for the condition input. This match type can be used only for distributed rules.
IsDirectory – This match type is used to determine whether the input string contains a physical path to a directory on a file system. If a condition input string is not specified, the URL Rewrite Module uses the physical path of the requested file as a default value for the condition input. This match type can be used only for distributed rules.
Pattern – This match type is used to express a condition where an arbitrary input string is matched against a regular expression pattern. A condition pattern can be specified by using either regular expression syntax or by using wildcard syntax. The type of pattern to use in a condition depends on the value of the patternSyntax flag defined for the rule to which this condition belongs. This condition type has two related attributes that control pattern matching:
In addition, the result of the condition evaluation can be negated by using the negate attribute. This can be used to specify a condition that checks if the requested URL is NOT a file, as in the following example:
Rule action
A rewrite rule action is performed when the current URL matches the rule pattern and the condition evaluation succeeded (depending on the rule configuration, either all conditions matched or any one or more of the conditions matched). There are several types of actions available, and the type attribute of the configuration element can be used to specify which action the rule performs. The following sections describe different action types and the configuration options related to specific action types.
Rewrite action
A Rewrite action replaces the current URL string with a substitution string. A substitution string must always specify the URL path (for example, contoso/test/default.aspx). Note that substitutions that contain a physical path on a file system (for example, C:\inetpub\wwwroot ) are not supported in IIS.
A Rewrite action has the following configuration options:
url – This is the substitution string to use when rewriting the current URL. The substitution URL is a string value that can include the following:
appendQueryString – Specifies whether the query string from the current URL is preserved during substitution. By default, if the value of the appendQueryString flag is not specified, it is assumed to be TRUE. This means that the query string from the original URL is appended to the substituted URL.
Redirect action
A Redirect action instructs the URL Rewrite Module to send a redirect response back to the client. The redirect status code (3xx) can be specified as a parameter for this action. The Location field of the response contains the substitution string specified in the rule.
The substitution URL for the redirect rule can be specified in one of the following forms:
Usage of a Redirect action implies that no subsequent rules evaluated for the current URL after redirection is performed.
A Redirect action has the following configuration options:
url – Uses a substitution string as a redirection URL. A substitution URL is a string that can include the following:
appendQueryString – Specifies whether the query string from the current URL should be preserved during substitution. By default, if the AppendQueryString flag is not specified, it is assumed to be TRUE. This means that the query string from the original URL is appended to the substituted URL.
redirectType – Specifies the status code to use during redirect:
CustomResponse action
A CustomResponse action causes the URL Rewrite Module to respond to the HTTP client by using a user-specified status code, subcode, and reason. Use of a CustomResponse action implies that no subsequent rules are evaluated for the current URL after this action is performed.
CustomResponse action has the following configuration options:
AbortRequest action
An AbortRequest action causes the URL Rewrite Module to drop the HTTP connection for the current request. The action does not have any parameters. Use of this action implies that no subsequent rules are evaluated for the current URL after this action is performed.
None action
A None action is used to specify that no action is performed.
Using server variables in rewrite rules
Server variables provide additional information about current HTTP requests. You can use this information to make rewriting decisions or to compose the rewritten URL. Server variables can be referenced in the following locations within rewrite rules:
In the condition input string
In rule substitution strings, specifically:
Server variables can be referenced by using the
Server variables can also be used to access HTTP headers from the current request. Any HTTP header supplied by the current request is represented as a server variable that has a name generated in accordance to this naming convention:
For example, in order to access the HTTP header «user-agent» from a rewrite rule, you can use the
Using back-references in rewrite rules
Parts of rules or conditions inputs can be captures in back-references. These can be then used to construct substitution URLs within rules actions or to construct input strings for rule conditions.
Back-references are generated in different ways, depending on which kind of pattern syntax is used for the rule. When an ECMAScript pattern syntax is used, a back-reference can be created by putting parenthesis around the part of the pattern that must capture the back-reference. For example, the pattern (4+)/([a-z]+).html will capture 07 and article in back-references from this requested URL: 07/article.html. When «Wildcard» pattern syntax is used, the back-references are always created when an asterisk symbol (*) is used in the pattern. No back-references are created when «?» is used in the pattern. For example the pattern */*.html will capture contoso and test in back-references from this requested URL: contoso/test.html.
Usage of back-references is the same regardless of which pattern syntax was used to capture them. Back-references can be used in the following locations within rewrite rules:
In condition input strings
In rule actions, specifically:
In a key parameter to the rewrite map
Back-references to condition patterns are identified by
For example, in this pattern:
For the string: www.foo.com the back-references will be indexed as follows:
Within a rule action, you can use the back-references to the rule pattern and to the last matched condition of that rule. Within a condition input string, you can use the back-references to the rule pattern and to the previously matched condition.
The following rule example demonstrates how back-references are created and referenced:
Interaction with IIS Output Caching
The URL Rewrite Module controls the IIS output cache behavior in order to:
The module controls output caching either by altering certain caching properties or by disabling the caching altogether. The module cannot enable output caching if it has been disabled by IIS configuration or by any other module in the IIS pipeline. The output caching is controlled as follows:
The module always sets the user mode cache setting varyByHeader=»HTTP_X_ORIGINAL_URL». This ensures that when user mode caching is enabled the module takes into account the original URL to construct a key for the cache entry.
If a rewrite rule set uses server variables with values that are either constant throughout the life of the process or are derived from the requested URL, the rule set is considered safe for output caching. This means that the URL Rewrite Module will not alter existing caching policy in any way other than setting varyByHeader as described in step 1.
The following server variables, when used in rewrite rules, do not cause any effect on output caching policy:
If a rewrite rule set uses any server variable not mentioned in the above list, the rule set is considered unsafe for output caching. This means that the URL Rewrite Module will disable kernel mode caching for all requests whether the request URLs were rewritten or not. In addition, the module will alter the caching policy for user-mode cache by setting the caching property varyByValue to contain the concatenated string of all server variables values used in the rule set.
String functions
There are three string functions available for changing the values within a rewrite rule action, as well as any conditions:
The functions can be invoked by using the following syntax:
Where «function_name» can be on eof the following: «ToLower», «UrlEncode», «UrlDecode». «Any_string» can be either a literal string or a string built by using server variables or back-references. For example, the following are valid invocations of string functions:
The string functions can be used in the following locations within rewrite rules:
In condition input strings
In rule substitution strings, specifically:
An example of a rule that uses the ToLower function:
An example of a rule that uses the UrlEncode function:
An example of a rule that uses the UrlDecode function:
Rewrite maps
A rewrite map is an arbitrary collection of name-value pairs that can be used within rewrite rules to generate the substitution URL during rewriting. Rewrite maps are particularly useful when you have a large set of rewrite rules and all of these rules use static strings (that is, when there is no pattern matching used). In those cases, instead of defining a large set of simple rewrite rules, you can put all the mappings into the rewrite map as keys and values between the input URL and the substitution URL. Then, to look up the substitution URL based on the input URL, you will have one rewrite rule that references the rewrite map.
A rewrite map defines a named collection of name-value pair strings, as in the following example:
A rewrite map is uniquely identified by its name and can contain zero or more key-value entries. In addition, a rewrite map can specify the default value to use when a key is not found. This is controlled by using the defaultValue attribute. By default, an empty string is used as a default value.
There can be any number of rewrite maps on any configuration level, except the file level. Rewrite maps are located within collection element.
Rewrite maps are referenced within a rewrite rule by using the following syntax:
Where the Key parameter can be any arbitrary string, and can include back-references to rule or condition patterns. For example, the following are valid uses of a rewrite map:
A reference to a rewrite map gets substituted with the value that was looked up by using the key passed as a parameter within a rewrite map reference. If a key was not found, the default value for that rewrite map is used.
A Rewrite map can be referenced in the following locations within rewrite rules:
In condition input string
In rule substitution strings, specifically:
Example 1: With a rewrite map defined as follows:
And a rewrite rule defined as follows:
Example 2: With a rewrite map defined as follows: