Fabrice's weblog

Tools and Source

News

My .NET Toolbox
An error occured. See the script errors signaled by your web browser.
No tools selected yet
.NET tools by SharpToolbox.com

Read sample chapters or buy LINQ in Action now!
Our LINQ book is also available on AMAZON

.NET jobs

Emplois .NET

transatlantys hot news

Contact

Me

Others

Selected content

ASP.NET HTTP module for URL redirections

For my own web sites, I needed to perform multiple URL rewritings, both in order to get short URLs and to charm Google and friends. You can see this at work for the SharpToolbox for example.
I improved Fritz Onion's HTTP Module, which performs redirects based on entries in your web.config file. It is regular expression-based, and is an easy way to perform automatic redirection for one set of URLs to another in your site.

I improved performance by keeping Regex instances, and added support for the ~ character.

Here is what the config file can look like:

<redirections type="Madgeek.Web.ConfigRedirections, Madgeek.RedirectModule">
 
<add ignoreCase="true"
   
targetUrl="^~/FalseTarget.aspx"
   
destinationUrl="~/RealTarget.aspx"
/>
 
<add permanent="true"
   
targetUrl="^~/2ndFalseTarget.aspx"
   
destinationUrl="~/RealTarget.aspx"
/>
 
<add
   
targetUrl="^~/(Author|Category|Tool)([A-Za-z0\d]{8}-?[A-Za-z\d]{4}-?[A-Za-z\d]{4}-?[A-Za-z\d]{4}-?[A-Za-z\d]{12}).aspx$"
   
destinationUrl="~/Pages/$1.aspx?$1=$2"
/>
  <add
   
targetUrl="^~/SomeDir/(.*).aspx\??(.*)"
   
destinationUrl="~/Pages/$1/Default.aspx?$2"
/>
</redirections>

I joined a small demo to the source code. Download.

Update: 2004/11/19 - added support for ignoring case. See the ignoreCase attribute.
Update: 2005/05/12 - works with .NET 2.0, you just have to replace the calls to ConfigurationSettings.GetConfig() by calls to the new ConfigurationManager.GetSection()

Comments

TrackBack said:

# November 18, 2004 5:10 AM

TrackBack said:

# November 18, 2004 5:47 AM

Mark Dicken said:

I'd be interested in a SQL Server Table based solution rather than redirects based on entries in your web.config. (especially if you have more than 1000+ possble 'virtual paths'

Has anyone implimented this ??? if so this could save me looking into this as its once one of my lists to do !!!

(I'm not too concerned with regular expressions as i have a complete list of 'virtual folders' to match against)

Regards

Mark Dicken
http://www.MarkDicken.com
# November 18, 2004 2:02 PM

TrackBack said:

# November 18, 2004 11:24 PM

TrackBack said:

# November 18, 2004 11:26 PM

TrackBack said:

# November 19, 2004 12:02 AM

Scott Galloway said:

Very nice work Fabrice!
# November 19, 2004 5:58 AM

Chris Martin said:

Mark,

What I do is write a mapping XML file in combo with a HttpModule that will read the request and look up the real path through XXXPath ;)

That gives me a lot of leverage because I don't have to manually add new pages to a config file. It's being generated everytime a page gets saved/updated.
# November 19, 2004 7:32 AM

TrackBack said:

# December 1, 2004 5:44 PM

TrackBack said:

# December 1, 2004 5:46 PM

TrackBack said:

# January 9, 2005 10:36 AM

Narendra Tiwari said:

# May 23, 2006 5:26 AM

Shawn said:

Hello Fabrice. This is a great article! I wonder, I am trying to build a redirect tool like TinyUrl.com and want to know if its possible to use this to detect ONLY files with NO extention. For example: http://MySite.com/SomeUserName Can I REGEX to detect just those instances of the above example? Thank you, -- shawn
# July 24, 2006 4:51 PM

Fabrice Marguerie said:

You can, but this requires having all HTTP requests redirected to your application.

By default, only "standard" ASP.NET requests are handled by ASP.NET applications. This means that you can process, an so redirect, only requests to .aspx, .asmx and .ashx documents. In order to get all requests redirecte to your application, you need a special configuration to be set in IIS. This may be difficult to get from your hoster, so you'd better check if they allow you to do that. Ask them if they can map .* to your ASP.NET application.

# July 24, 2006 5:01 PM

Travel in Romania said:

To map all the requests to asp.net engine is a solution but might be a little difficult and you can have problems when deploying, I was looking for a solution because I'm working right now on building a asp.net blog and I'm using url rewriter. The problem is I don't want to create dummy directories to contain empty default.aspx pages. From IIS right click on your virtual directory then go to Custom Errors and edit properties for 404 error code, change the Message Type drop down to URL and add an aspx page instead (something like this: /Blog/404error.aspx). This means every missing pages will end up by calling 404error.aspx. At this moement if you access a subdirectory that does not exists the IIS should try execute 404error.aspx page. At this point you can see the original request from the QueryString and use it in url rewriter. Sorry for my bad english.

# August 22, 2006 9:50 AM

Nathan said:

Hi - this is great- but i'm a newbie to this world - i've got a vb.net asp.net app - i can see that this is a c# app - can i integrate this with my vb.net app?

thanks

# August 22, 2006 4:50 PM

Fabrice Marguerie said:

Nathan, everything that is written in C# can be used as-is in VB.NET, and vice-versa. C# and VB.NET are two languages that work on the same platform and runtime (.NET).

# September 6, 2006 6:46 AM

Dave J said:

I've been using this for a while now and it has been excellent. However I have just come across a problem. I need to use both URL rewriting and redirects (to redirect from "moved permanently" pages using an HTTP 301). However both Http module I need to use for this want to use <configuration><appSettings><redirections></redirections></appSettings></configuration> in my web.config, and of course .NET won't allow this. Is this section name specified in the module itself? If so, would it be possible to change the section name to something more specific to the module, like or something?
# September 30, 2006 9:22 AM

Fabrice Marguerie said:

Dave, yes, feel free to do the change in the source code.

# September 30, 2006 10:41 AM

Dave J said:

OK I've only just realised this module can do both URL rewriting AND 301 permanent redirects. I was trying to use two seperate http modules, when I could use this one for both. Duh.
# October 1, 2006 5:47 AM

Dmitry said:

Hi! Great article. But I'm expiriencing such problem: I have a rule From "~/1/Target.aspx" to "~/Default.aspx?JobPostingID=1". And it works fine - it redirects me to Default.aspx and I have access to QueryString. But when I have postback on this page I get the error "The resource cannot be found" - "1/Default.aspx". Could you help me with this? How to process postbacks? Thank you.
# October 4, 2006 6:50 AM

Fabrice Marguerie said:

Dmitry, to find out how to have postbacks working correctly, you can take a look at the following articles:

http://msdn.microsoft.com/library/en-us/dnaspp/html/urlrewriting.asp

http://weblogs.asp.net/jezell/archive/2004/03/15/90045.aspx

# October 4, 2006 9:09 AM

Fabrice's weblog said:

In a comment to an old post of mine about URL rewriting, a visitor named Tim has just asked how to solve
# October 19, 2006 8:52 PM

oyun oyunlar said:

Has anyone implimented this ??? if so this could save me looking into this as its once one of my lists to do !!!

# August 31, 2007 4:29 PM

Ramanathan said:

Hi,

well this URL redirections works well, I have to get the new url (dummy) to be created without hardcoding as did .   i,e if in a page it was already there like Response.Redirect("~\search.aspx?ptype=hotel"). I need to rewrite this url to "~\search\hotel.aspx" and then redirect to that url. have anyone implemented this.

Reply if done. thanks in advance

# September 28, 2007 8:36 AM

lance said:

In response to Fabrice's posting above, I created a mapping:

Executable: c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll

Extension: .*

Verbs

Limit To: GET,HEAD,POST,DEBUG

Script engine: checked

check file exists:  checked

This works great except for one thing. Now IIS does not pick up the Default document types in folders (Default.aspx). For example, I have a link to /SiteRoot/Register/, this takes users to /SiteRoot/Register/Default.aspx. Any ideas on how I can keep the .* mapping, but also allow IIS to pickup the default documents (default.aspx)?

# October 18, 2007 7:38 PM

Fabrice Marguerie said:

Lance, you should be able to use a rewriting or a redirection from /SiteRoot/Register/ to /SiteRoot/Register/Default.aspx in your configuration file.

# October 18, 2007 8:06 PM

Euro 2008 said:

Hello Fabrice. This is a great article! I wonder, I am trying to build a redirect tool like TinyUrl.com and want to know if its possible to use this to detect ONLY files with NO extention. For example: http://MySite.com/SomeUserName Can I REGEX to detect just those instances of the above example? Thank you, -- shawn

# May 13, 2008 2:50 AM

Fabrice Marguerie said:

This should be possible. All you need is to find the correct regular expression.

# May 13, 2008 7:17 AM

Town said:

This works fine under the local asp.net server but i'm getting 404s when i deploy with IIS (5), i assume IIS is taking the www.mydomain.com/mypage/myparameter URL format and attempting to navigate straight to that directory.

Has anyone else come up against this issue and found a workaround? Thanks.

# June 23, 2008 6:51 AM

Fabrice Marguerie said:

Town, in IIS 5 there is an option to "Check File Exists" on the "Add/Edit Application Extension Mapping" screen. Make sure it's off.

# June 23, 2008 7:10 AM

Town said:

Hi Fabrice, thanks for the reply.  That setting looks to be a per-extension setting, which extension does it need to be set for?  It's already off for .aspx files.

Thanks.

# June 23, 2008 9:42 AM

Fabrice Marguerie said:

If all you use is .aspx, then it looks like your problem comes from something else.

If you use another extension or no extension (* or .*), then make sure the option is off for them too.

# June 23, 2008 9:55 AM

Emmanuel LANDREAU said:

Hello,

I using this URlRewriting Module to rewrite and to redirect...

I'm using rules with redirectMode="Permanent" but I still have a 302 redirection. That is quite strange? Do you have any good example for 301 redirection?

Thanks for your help!

# September 25, 2008 1:27 PM

Fabrice Marguerie said:

Hi Emmanuel,

There is no redirectMode attribute in this rewriting module. You should use permanent="true", as in the sample provided in this post.

Fabrice

# September 25, 2008 1:36 PM

Umid said:

This is great tutorial for url rewriting , thanks!

And here how to register this module for IIS7:

open web.config then just add one line:

<system.webServer>

  <modules>

    <add name="rewriteModule"  type="Madgeek.Web.RedirectModule" />

  </modules>

</system.webServer>

That's it!

# January 13, 2009 1:38 AM

Fabrice Marguerie said:

Umid, I don't think that this is any different than with any other version of ASP.NET. It doesn't look specific to IIS 7.

# January 17, 2009 3:08 PM

tisa said:

Hi Fabrice, thanks for your article, it let me know more about the redirect url knowledge. but i have problem when i use your demo to see the result, and i got the following problem, could you help me to solve it??

"Parser Error Message: Could not load type 'RedirectModuleDemo.Default'." and

Line 1:  <%@ Page language="c#" Codebehind="Default.aspx.cs" AutoEventWireup="false" Inherits="RedirectModuleDemo.Default" %> in default.aspx

Thanks!

# February 20, 2009 10:56 PM

Fabrice Marguerie said:

Hi Tisa, this error doesn't seem to be  related to URL rewriting. Have you changed anything in the source code of the demo? Which version of Visual Studio are you using?

# February 21, 2009 7:35 AM

Tisa said:

Hi Fabrice,

Thanks for your reply. MY visual studio 2003 and .Net Framework is 1.1. Actually i didit create the project, i just copy your demo folder under C:\Inetpub\wwwroot\Demo, and run it as localhost/.../default.aspx

# February 21, 2009 9:59 AM

Fabrice Marguerie said:

I haven't used VS 2003 for many years now, but I wonder why you copied the demo folder. I think you should instead leave the files all in one place, create an IIS application on the Demo folder, and then open the solution in VS and run the project from there.

It looks to me as if you haven't built the project...

# February 21, 2009 7:06 PM

tisa said:

Hi Fabrice,

Thanks for your reply. Now it is working when run your demo. But i don't see any redirect action. when i click FalseTarget.aspx link, it is not go to realTarget.aspx, do i have something need to set before run this program? is it relate to the programming language c#??

# February 23, 2009 4:31 AM

Fabrice Marguerie said:

> "when i click FalseTarget.aspx link, it is not go to realTarget.aspx"

What happens instead? Do you get an error? Without more information, I'm not able to help you.

# February 23, 2009 5:54 AM

tisa said:

Hi Fabrice,

It doesn't have any error. it just show HTTP 404 error code. I think it only mean the file cannot be found.

Thanks!

# February 23, 2009 6:44 AM

Fabrice Marguerie said:

Tisa, it seems that you need to make sure that "Check that file exists" is unchecked for the .aspx extension mapping in IIS.

# February 23, 2009 7:12 AM

tisa said:

Hi

It is work now. Thanks for your reply. i have another question. I know that the demo can redirect the FalseTarget.aspx to RealTarget.aspx. But If i have the following situation what can i do. Actually i need to create one website and user click the url like this http://localhost/main/123/456/(the actual link like this locathost/main.aspx)and the system can know that 123 is brandId and 456 is catgId and find out the related information. But in the url toolbar , user only can see that link is http://localhost/main/123/456/ not locathost/main.aspx.

Can you get my meaning?

Sorry for that i have many question=_=

# February 23, 2009 8:44 AM

Fabrice Marguerie said:

There are many solutions for this kind of need:

- This HTTP module is here for that.

- Personally I've used my own PageMethods library (metasapiens.com/PageMethods), but the current public version doesn't offer integrated support for URL rewriting.

- I've also used other URL rewriting libraries. See sharptoolbox.com/.../urlrewritingnet-urlrewrite or sharptoolbox.com/.../nurlrewriter or sharptoolbox.com/.../urlrewriter-net

In any case, you'll have to map .* to aspnet_isapi.dll. See the above comments, such as this one: weblogs.asp.net/.../265719.aspx

# February 23, 2009 2:26 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)