advanced web statistics

Rewrite URL Without Using Filenames or Extensions (C#)

4/1/2006 12:23:33 PM

I`ve finally done it! People have been asking on my previous post about URL Rewriting via Global.asax if it is possible to rewrite a URL without using .aspx, .asp, .html, or any other file extension.  It seemed that the general consensus was that settings needed to be changed in IIS or that it simply wasn`t possible.  Well my friends, I have figured it out.  Building upon my theory of creating post slugs for each entry.

Before we begin let me explain what a "slug" is.  There have been many definitions I have come across trying to define them but the best that I've found is that they are a unique page identifier used (mainly by blog and commerce sites) for the purpose of making a more human and search-engine friendly URL.

Example
http://www.willasrari.com/blog/post.aspx?post=404&date=102005&t=Welcome (bad)
http://www.willasrari.com/blog/title-of-my-post-or-product-title-goes-here/ (good)

You can see that the bottom URL looks friendly and it doesn't take a rocket scientist to figure out that if you submit sites with many URL's following this convention to search engines that you will get better rankings. You must also name your entries (or slugs) very descriptively (word?) and relevant to the content of the entry and yada, yada, yada.... But you get the idea right?

How to accomplish this?
First you must use a field in your database for a slug. If you don't already have one (which I'm sure many of you don't) you can easily create one.  Just create a field for text values and loop through your entry titles creating the slugs.  They have to be unique!  I will post code for this at a later time.

Once you have a unique identifier (slug) for each entry you can then create a Regular Expression in your Global.asax file in the Application BeginRequest method to look for everything between "/" and "/" in the current URL. So /directory/blog-post/ would be pulled. Then you run this through a replace function to get "blog-post" and send this string to your database to get the ID for the entry (or product) and then rewrite the path to appropriate page.

Global.asax Code (C#) (Application_BeginRequest)

protected void Application_BeginRequest(object sender, EventArgs e)
{
   HttpContext httpContext = HttpContext.Current;
   Regex pattern = new Regex(@"(.+)\/", RegexOptions.IgnoreCase);
   Match matches = pattern.Match(httpContext.Request.Path);
   string slug = matches.ToString().Replace("/Rewrite/", "").Replace("/", "");

   if (!string.IsNullOrEmpty(slug))
   {
      int pageId;

      using (OleDbConnection cn = new OleDbConnection(""))
      using (OleDbCommand cm = new OleDbCommand("GetEntryIdBySlug", cn))
      {
         cn.Open();
         cm.CommandType = CommandType.StoredProcedure;
         cm.Parameters.AddWithValue("@slug", slug);
         pageId = (int) cm.ExecuteScalar();
      }

      httpContext.RewritePath(string.Format("~/entry.aspx?ID={0}", pageId));
   }
}

I have included the Visual Studio 2005 Solution file. I also do not have time (at this time) to fully explain every line of code. The solution file that I provide is well-commented.  I do plan on creating another entry that steps through the concept more.

One Last Thing
You might be wondering how to create a slug field that is browser/url-friendly. Here is the method that I use.

public string CreateFileSlug(string original)
{
   return Regex.Replace(original, @"[^\w\@-]", "-").ToLower();
}

Thanks to Bobby for engaging in dialogue and inspiring me to look more into this. The solution file is a directory named Rewrite. Simply extract the contents of the .zip file into a directory in wwwroot called Rewrite.

Have fun! Please link to this article if you find my code useful. I'm sure there are plenty of people that would benefit from this.

UPDATE
I am in the process of rewriting this to extend functionality. Possibly with & without slugs!

Attachments
Download the Visual Studio 2005 Solution, Microsoft Access 2003 Database

.NET, C#, Code, Programming, SEO

kick it on DotNetKicks.com

Comments


Hey Will, nice article. You definitely show how to use the title of the article to create a better looking URI. Having said that, I`m sorry to disappoint you but the solution will not work unless your IIS has been previously tweaked or changed from the default installation.

I`m not sure if I haven`t explained it clearly or where the lack of communication is, but without changing the application mappings in IIS the global.asax file will never be called. From a default installation of IIS you can look at the properties of the "Default Web Site." Under the "Home Directory" tab you will see the "Configuration" button. From the window which opens you should see a list of extensions and applications that process them.

As you can see, by default the asp_isapi.dll doesn`t not handle all requests and must be set to for your solution to work. http://www.codeproject.com/aspnet/URLRewriter.asp is a great article which explains why you will always have to alter IIS settings if you wish for for your solution to work.

-B

Posted by: Bobby | 4/3/2006 12:34:52 AM

Sorry about that Bobby. I don`t know how to configure IIS to call Global.asax.

I will definitely look more into this. Let me first re-deploy this on my server and test again.

So this solution doesn`t work for you at all on your machine? What happens when you open in Visual Studio 2005 and debug?

Posted by: Will | 4/3/2006 10:50:15 AM

The solution you`ve provided works great if I allow the ASP.NET Development Server to act as the webhost. If I upload the compiled site to my webhost it doesn`t work and I get a page not found when attempting to access the fake directories - letting me know that global.asax was not called.

I have no doubt about the ability of your solution to display the correct entry based on the title slug.

It appears that this still isn`t a general solution for those wanting to create URI`s without extensions and do not have access to their IIS settings.

-B

Posted by: Bobby | 4/3/2006 7:50:38 PM

Oh well, it worked in theory right?

I`m looking at it positively though. I too got the same error when running on IIS (shared hosting) and found a workaround. If you do post-slug/default.aspx it will work. This means that we are 1 step closer to extension-less URL`s.

Thanks for the feedback.

- Will

Posted by: Will | 4/3/2006 8:47:47 PM

very worst code

Posted by: pranay | 5/24/2006 12:31:35 AM

You should probably add or write some better code instead of complaining about mine.

Ridiculous.

Posted by: Will | 5/24/2006 11:00:18 AM

if you get IIS to forward the 404 error you get when only typing a url without a page name, then the global.asax will interupt that request and still fire. All you have to do is grab the url from the querystring instead or the request.incoming....

just implemented it for the new Casio UK site, which is going live in the next few weeks.

Hope i make sense.

Posted by: Andrew Clarke | 6/1/2006 5:23:56 AM

Makes total sense Andrew. That wouldn`t be the same as custom 404 error pages in web.config would it?

I`m on shared hosting so I can`t hack at IIS.

Posted by: Will | 6/1/2006 9:29:04 AM

Hi

Could I, using this code make that when user type like /Rewrite/FolderName(without .aspx) - witch doesnt exist, I capture that foldername, get ID from db using that foldername,and then redirect(rewrite) to /Rewrite/FolderName(fake)/index.aspx with ID in querystring

Posted by: Petar | 7/24/2006 9:21:41 AM

Petar,

You can do that but you will have to follow the guidelines left by Andrew Clarke above.

Thanks for the feedback. The limitation on this code is that if you are on shared hosting (i.e. no access to IIS) then you have to type /Rewrite/FolderName(fake)/default.aspx. I don`t know why you would want querystring to show in the URL since you are rewriting the path using the querystring ID. Even though you can`t actually the querystring it is still there and you can access it programatically.

- Will

Posted by: Will | 7/28/2006 11:09:11 AM

Will,
This post proved most helpful. With only slight modifications, I was able to get this working.
- Brian

Posted by: Brian | 8/7/2006 4:46:57 PM

I`m glad I could help Brian.

Posted by: Will | 8/7/2006 6:37:15 PM

This may be a dumb question, but how do you get IIS to forward the 404 error only when typing a url with out a page name?


Posted by: Miguel | 9/29/2006 12:43:01 PM

Miguel,

Sorry it took awhile to get back. I don`t think you have to have IIS to forward the 404.

I believe you can do this from the web.config with a custom 404.

Thanks for visiting!

- will

Posted by: Will | 10/4/2006 4:10:32 PM

hi.

this is great stuff!
but no-one has explained exactly how to configure IIS to make this work.

The instructions on the link provided by bobby will not work on IIS6 as IIS^ will not take a wildcard file extention.

Any help great appreciated.

Thanks,
Dave

Posted by: dave | 10/26/2006 5:12:10 PM

I made some customization on the code and it's running on a simple website with one page like you did, but when I putted it into my project it has a masterpage and menu controls and alot of stuff, when i debug the code i see that he captured /webproject/WebResource.axd like four or five time and if I like to go to page http://localhost/webproject/page/123/ then I got 404 error but when i run it on a simple project it works !! so do you have an explanation for this? regards

Posted by: ProfessorX | 12/18/2006 7:20:32 AM

Not sure if this has been totaly dropped, but I am still trying to fix this problem.

What I am chasing and not getting any answers or help from the .net community is this idea.

Intercept the requested Url using the Global.asax, grab the Url String check to see if it ends in ".aspx" if it doesn`t re-write the Url and add .aspx extension to it.

You now have a properly formed Url with extension that you can apply url re-writes rules to.

http://forums.asp.net/1651604/ShowThread.aspx#1651604

Posted by: Aaron | 4/4/2007 1:01:32 PM

You finally done it, aaaeeeee)))
the biggest respect from all my company and personally from me:)

Posted by: harry | 4/12/2007 6:28:23 PM

HELP!!!

Has anyone got example code redirecting from the 404 error page.


Posted by: Kali | 4/22/2007 3:33:08 PM

It`s quite effective and fast method of rewriting URL...respect!

Posted by: trenton | 4/25/2007 8:17:45 PM

This post proved most helpful. With only slight modifications, I was able to get this working.

Posted by: Garry | 5/19/2007 2:43:31 PM

This post proved most helpful. With only slight modifications, I was able to get this working.

Posted by: Garry | 5/19/2007 2:44:22 PM

Hello man and good luck man ;)
Excellent blog.

Posted by: Mack | 5/21/2007 3:44:50 PM

I`m looking at it positively though. I too got the same error when running on IIS (shared hosting) and found a workaround. If you do post-slug/default.aspx it will work. This means that we are 1 step closer to extension-less URL`s.


Posted by: trenton | 5/21/2007 7:38:10 PM

Hello! It`s very interesting things.
Thank you for this ;)

Posted by: Peter | 5/23/2007 2:14:27 AM

This may be a dumb question, but how do you get IIS to forward the 404 error only when typing a url with out a page name?

Posted by: Jimmy | 5/25/2007 3:31:49 PM

It`s quite effective and fast method of rewriting URL...respect!

Posted by: Jess | 5/30/2007 12:57:35 PM

Thanks it really works!

Posted by: Kesha | 6/6/2007 8:51:22 PM

Hey your solution is gr8 but i am facing a problem. i am working in .net 2005 and implemented URL Rewriting. It works fine in case of normal pages but creates an error on those webpage on which i hav implemented AJAX
CAN U HELP????

Posted by: harpreet | 6/13/2007 12:56:03 AM

Thanks, excellent piece of code!
http://www.vannin.ch/Pages/blog/ryan/07/07/07/search-engine-optimization-alla-ticinese.aspx

Posted by: Ryan | 7/10/2007 4:26:06 AM

The problem with having to configure IIS to pass all extensions to ISAPI dll is solved in IIS 7. So you can use extension-less URL nicely :)

Posted by: Learner | 7/11/2007 6:23:34 AM

I`m on shared hosting (currently) so I will never have the luxury of fussing with IIS. As was stated before, just append "default.aspx" to this newly created slug and it will work on shared hosting.

Thanks for the comment.

Posted by: Will | 7/11/2007 11:53:42 AM

Very useful and effective!Thanks!Good luck!

Posted by: Smeli | 7/31/2007 12:04:40 PM

thanks!

Posted by: barda | 8/13/2007 11:31:13 PM

It`s not comment question,
I want to rewrite the path as below
initial url: http://www.abc.com/product.aspx
new path should be:- http://www.abc.com/product.html

is it possible without configuring the iss extension mapping

Posted by: Dibya Mani Svuedi | 9/14/2007 1:30:31 AM

Dibya,

As far as I know you HAVE to configure IIS. If there is another way I am ALL ears!

- will

Posted by: Will Asrari | 9/14/2007 11:18:50 AM

Any plans to put the code backup?

Posted by: primortal | 9/30/2007 1:49:29 PM

Yes I am. I`ve been extremely busy lately and haven`t yet been able to finish up and put back online.

Posted by: Will Asrari | 9/30/2007 2:18:54 PM

Seems like using the custom error page to handle 404s is the best way to do it, as you can custom write your 404 handler script to parse the URL. I have used it for both ASP.NET and also PHP when run on IIS6 (a non-ideal platform!). I just wished microsoft would make IIS like Apache with its RewriteRules.

Posted by: CodeStar | 2/1/2008 1:37:53 AM

Hi will,
This is a nice article but i am not able to download the code.. plz update the code online.
if possible plz give step by step detail , so that i can use it in my project.

Greate post.. !!!
All the Best

Thanks & Regards
nn

Posted by: nn | 3/24/2008 7:38:53 AM

hi If possible then please send me working example of url rewriting in c# in my mail id which is milap@netedgetechnology.net. Thanks in advance.

Posted by: milap | 5/5/2008 5:17:45 AM

Good one

Posted by: Naison Garvasis | 5/19/2008 6:21:40 AM

hi If possible then please send me working example of url rewriting in Asp.net(c#) in my mail id which is divkudilil@yahoo.com. Thanks in advance.

Posted by: Divya | 5/20/2008 7:53:00 AM

Can u plz help me solve one problem regarding URl Rewriting
Problem

WhenEver one can type www.xyz.com/category.aspx?NodeID-1234

then the same page will open but with the url
www.xyz.com/category-1234.

Means page open with different URL.

Please send me the sample code as soon as posible.

Thanks

Posted by: ankur Pandit | 5/29/2008 12:06:00 PM

Hello Mate,

I could not download the source code.

Can you please email me

Thanks a ton

Posted by: Jay | 7/22/2008 12:28:05 PM

Hi.
I have a problem when i try to run this under dotnet 3.5 VS-2008 and IIS 5.0.
The problem is that when the link is being clicked before going to the Global.asax Application_Beginreques the page returns HTTP Error 400 - Bad Request becaus that kind of filename doesn`t exeists on the server(the check on the IIS mappings is absent for the realted file extention IIS didn`t check the filename for existence for this extention). If I do the same on the dot net 2.0 VS 2005 with ASP.Net 2.0 everything works OK.
If you have a solution to this please email me if it is not dificult for you.
Tanks in advance.

Best Regards.

Posted by: Suren | 9/13/2008 7:34:42 AM

agood

Posted by: pran | 9/29/2008 1:50:54 AM

Hi Will,

The Download link on this post appears to be broken.

Cheers!

Jean-François

Posted by: JF | 11/26/2008 4:39:17 PM

thanks for your article.

Posted by: vinh | 1/13/2009 4:14:53 AM

mmnmn

nk



























cdvcvcvcv

Posted by: dsfdsf | 7/6/2009 12:32:31 PM

mmnmn

nk



























cdvcvcvcv

Posted by: dsfdsf | 7/6/2009 12:32:34 PM

This one is really useful for me, thanks for sharing.

Posted by: SEO Services | 7/18/2009 2:02:32 AM

ltdnaewx http://jxflontl.com qvhbpivf uafrlimc

Posted by: hylftqiv | 9/7/2009 3:12:35 PM

I lived what most people call the good life. I was happy, but deep inside I always felt that, with the short amount of time we are given to live and love in this world, we spend too much time loving things instead of people.

Posted by: levitra online | 9/9/2009 5:11:19 PM

cuifvbke http://rjovoybw.com psshghql bglcbcxr

Posted by: fqqxdwof | 9/10/2009 5:12:04 PM

We learn something every day, and lots of times it`s that what we learned the day before was wrong.

Posted by: cialis levitra | 9/11/2009 10:07:41 AM

The power of accurate observation is commonly called cynicism by those who have not got it.

Posted by: aciclovir | 9/11/2009 1:35:58 PM

mhrjytot http://xxuoqxit.com krrbnnjs qmiwlpcr

Posted by: rufskvpw | 9/12/2009 12:35:34 AM

Let us so live that when we come to die even the undertaker will be sorry.

Posted by: cialis tadalafil | 9/12/2009 5:36:12 AM

History is more or less bunk.

Posted by: abana | 9/12/2009 10:15:00 AM

I hope this will help for other users.
There you dont need any intraction with your IIS Server.If you deploy at your hosting shared machine. IT will work fine.

http://blog.joggee.com/?p=182
Just give a try and let me know..
Joggee

Posted by: Joggee | 9/27/2009 3:01:14 AM

I found your post really interesting. I found Internet marketing a really a great way of promoting a website. I found good results when I started internet marketing my website.

Posted by: Jeff Paul Shortcuts | 10/2/2009 2:46:01 PM

Great post! My friend runs a small business we do internet marketing for companies and so a lot of our e-newsletter, blog and seminar content revolve around for promotion. Thanks!!!

Posted by: Internet Marketing Success Stories | 10/8/2009 1:37:41 PM

Great work! What is discuss here is one side of the coin, what about social media, isnt it a challenge to google

Posted by: Jeff Paul Forum | 10/10/2009 1:09:50 PM

Really Nice Post. More and more businesses are indulge with online presence, it is costly if you find a wrong company to do your job

Posted by: Internet Business Review | 10/10/2009 2:39:41 PM

I like your post. No matter what amount of debt a person has, willingness to retire is the first step

Posted by: Michelle Boudreau | 10/12/2009 4:53:58 PM

It’s really amazing. Debt can be rescued by reducing expenses not by increase income

Posted by: Debt Rescue Relief | 10/14/2009 2:00:49 AM

Very Informative blog. This is true, in real estate investment foreclosure properties under tax lien is big investment

Posted by: Tax Foreclosed Properties | 10/18/2009 4:47:24 PM

Getting to know about the real estate investment starts with an understanding to worth of house / average worth of neighbours

Posted by: John Beck Tax Sales | 10/19/2009 5:22:17 PM

Its very intresting and Informative stuff. Women finds it difficult to manage their cost, save $1 a day and you can see the difference it makes

Posted by: Wealthy Women Debts | 11/19/2009 3:15:26 PM

I like your post. No matter what amount of debt a person has, willingness to retire is the first step

Posted by: Michelle Boudreau | 11/20/2009 1:50:19 PM

It’s really amazing. Debt can be rescued by reducing expenses not by increase income

Posted by: Debt Rescue Relief | 11/21/2009 1:26:07 PM

I believe the real estate market has much to offer, like what is being offered by John Beck in foreclosure properties

Posted by: John Beck Propery Vault | 11/21/2009 3:58:11 PM

Foreclosure properties are in high demand as the lenders are in troble and there are many tax foreclosure properties available

Posted by: Land Bank | 11/22/2009 1:05:14 PM

Very Informative blog. This is true, in real estate investment foreclosure properties under tax lien is big investment

Posted by: Tax Foreclosed Sales | 11/22/2009 4:15:35 PM

Getting to know about the real estate investment starts with an understanding to worth of house / average worth of neighbours

Posted by: John BeckTax Sales | 11/23/2009 1:27:42 PM

That`s great, I never thought about marketing like that before.Thanks for sharing

Posted by: Agenzia Web Marketing | 11/26/2009 1:01:11 AM

Thanks for sharing this article.That`s very helpful and interesting.

Posted by: traslochi a milano | 12/9/2009 1:00:16 AM

Leave a Comment

   

  Enter the text to proceed!