Redirect requests to your application with the HttpRedirection module

Download: HttpRedirection_v1_source.zip

The HttpRedirection module allows you to configure regular expression-based rules that redirect clients from url A to url B using http redirection.

When clients make a request to your server, and the url matches one of the redirection rules you have configured, the server will respond with a redirection response, telling the client to go to your redirected url to complete the request.  It will look something like this (standard redirection response):

HTTP/1.1 302 Foundrn
Date: Thu, 24 May 2007 21:32:05 GMTrn
Location: /redirection/users/mike/rn

rn
<html><head><title>Object moved</title></head><body>rn
<h2>Object moved to <a href=”/redirection/users/mike/”>here</a>.</h2>rn
</body></html>rn

The Location response header will indicate the redirected url to which the client will automatically redirect.  Some older browsers that don’t support this behavior (I don’t know of any at this point) will see the hyperlink and the user will be able to manually click it to go to the new url.

Deploy the HttpRedirection module in your application


IIS5
: The module can only redirect requests made to content-types mapped to ASP.NET.
IIS6: Same as IIS5, unless you configure the IIS6 / ASP.NET 2.0 wildcard mapping support (see the
how-to in the LeechGuard post).  Then, this module will be able to provide redirection for all requests.
IIS7: In Integrated mode applications, this module will by default provide redirection for all requests. 

Setting it up is simple:

1.       Download the sample application, and use it
OR

1.       Drop the module assembly into /BIN

2.       Register the <httpRedirection> configuration section in your web.config file, and configure the desired redirection rules as shown in the example app.

Create HttpRedirection rules for your application

The rules can be expressed in the <httpRedirection> configuration section in your web.config file, and allow you to set the following:

matchUrl

The regular expression matching the incoming request urls.

redirectUrl

The url to redirect to, which can contain regular expression references to capture groups from the matchUrl, allowing you to insert parts of the original url into the new url.

urlPart (optional, defaults to PathAndQuery)

The part of the incoming url to match: the entire url, or just the path and querystring, or path only.  Use this to avoid writing regular expressions to match more of the url then you care about.

redirectType (optional, defaults to Temporary)

The type of redirection you want: temporary, permanent, or see other.

requestStage (optional, defaults to BeginRequest)

The stage of the request processing during which you want the redirection to take place.  Can be BeginRequest, PostAuthenticate, or PostAuthorize

The matchUrl and redirectUrl can contain special variables that expand to various request parameters, including:

·         {Protocol} – the protocol scheme of the url

·         {Hostname} – the hostname of the url

·         {Port} – the port of the url

·         {Path} – the absolute path of the url

·         {Query} – the querystring.  Also {Query:Param} for a value of the specific QS parameter.

·         {SV:Param} – the value of a specific server variable (can use this to get any request header)

·         {User} – the name of the authenticated user

·         {Culture} – the culture for this user

·         {AppPath} – the application path for the current application

·         {DirectoryPath} – the directory path segment of the url

·         {FilePath} – the file path segment of the url

(If you are using the “{“ symbol as part of the regular expression in either matchUrl or redirectUrl, escape it by using “{{“)

You can also configure the redirection module to append the original url in the querystring with the appendOriginalUrl parameter on the <httpRedirection> section, and keep track of the redirection depth so redirection loops can be broken by configuring the maxRedirects parameter.

Here are some example rules you can start with:

<!– Redirect all requests to www.website.com to website.com –>

<addname=HostnameurlPart=EntireUrlmatchUrl=^{Protocol}://www.(w+.com.+)redirectUrl={Protocol}://$1 />

<!– Redirect to a localized version of the app –>

<addname=LocalizedApplicationurlPart=PathAndQuerymatchUrl=^{AppPath}/content/(.+)redirectUrl={AppPath}/content/{Culture}/$1 />

<!– Redirect all HTTP requests to application to HTTPS –>

<addname=SSLRedirecturlPart=EntireUrlmatchUrl=^http://(.+)redirectUrl=https://$1 />

<!– Redirect to the same url, placing the Referer http header in the querystring –>

<addname=PlaceRefererInQueryString_NoQueryurlPart=PathAndQuerymatchUrl=^{Path}$redirectUrl={Path}?referrer={SV:HTTP_REFERER} />

<addname=PlaceRefererInQueryString_WithQueryurlPart=PathAndQuerymatchUrl=^{Path}?((?!referrer).*)$redirectUrl={Path}?referrer={SV:HTTP_REFERER}&amp;$1 />

<!– Permanently redirect all requests to multiple product pages into a single product catalog with querystring –>

 

<!– Permanently redirect all requests to multiple product pages into a single product catalog with querystring –>

<addname=ProductCatalog_NoQueryurlPart=PathAndQuerymatchUrl=^{AppPath}/products/([^/]+).aspx$redirectUrl={AppPath}/products/catalog.aspx?productId=$1redirectType=Permanent />

<addname=ProductCatalog_WithQueryurlPart=PathAndQuerymatchUrl=^{AppPath}/products/([^/]+).aspx{Query}$redirectUrl={AppPath}/products/catalog.aspx{Query}&amp;productId=$1redirectType=Permanent />

The current version is v1.0, released on May 24, 2007.

1.     Download the module and the sample application.

2.     Download the source code (this code is distributed under the Microsoft Permissive License).

Let me know if you are using it, and if you have any questions / suggestions / complaints by leaving comments.

15 Comments

  1. Anonymous

    Sounds complicated for a simple aspnet requirement.

    If you move webpages and want all your clients to see the redirect upon any request then why not just create a default error in the web.config like:


    placed in the root directory and all old website content removed it should easily force everyone to the new site as a default error.

  2. Anonymous

    Is there a way to preserve Session state with this module so that, for example, a user could transgress across subdomains in the same session?

  3. Anonymous

    I tried to use this module with a website I am working on. It always gives the following error?
    The configuration section ‘httpRedirection’ cannot be read because it is missing a section declaration
    Could you help me out
    Here is the edited portion of the web.config file:

























  4. Anonymous

    is this doable in IIS6? Scenario:
    I have a subdomain – subdomain.mysite.com – that I want to be redirected to http://www.mysite.com. However, I need it to be applied for both https and http. I am using IIS6 currently. Any help is greatly appreciated!

  5. Anonymous

    I am trying to create an HTTPModule that will add a variable and value to the header and redirect the request to another external server (with the modified header). any ideas how I can acomplish this?

    Thanks!

  6. Anonymous

    I’d like to see some examples, and a general solution to redirecting from http:// to the same url with https://…:.
    This is because we need to support a number of SSL services on the same IP with different ports (because I don’t want to pay for a separate static IP for each separate SSL, and the SSLs are on different hosts behing the firewall), and having to remember the SSL ports is a hassle.
    Being able to accept http: connections that are redirected to the right SSL port would be easy to use.
    /kenw

  7. Anonymous

    I want the SSL Redirect for only certain pages example: whenever login page is accessed http:abc.comuserlogin.aspx, redirect to https:abc.comuserlogin.aspx.
    Can I have the IIS UrlRewriter rule for this?

    TIA,
    Prem

  8. Anonymous

    is there an easy way to re-direct requests to a folder to another folder, while preserving the rest of the path.

    e.g.

    If I have moved the content from:
    mysite.org.uk/stuff
    to
    stuff.mysite.org.uk/

    Can I automatically redirect requests for specific pages like
    mysite.org.uk/stuff/countrybriefing/tanzania/travel.html
    to
    stuff.mysite.org.uk/countrybriefing/tanzania/travel.html

  9. Anonymous

    Ok I thought I had this working but I have run into an issue.
    Here’s my rule:

    It works like a charm under Localhost/debug mode but when I try it from the web I get a 500 error. I was wondering if the fact that I am trying o use AppPath is the problem here and if it is what should I use in its place?

Leave a Reply

Your email address will not be published. Required fields are marked *