SEO Search Engine Friendly URLs with ASP.NET and IIS

I decided it was about time for another code update, and since there are plenty of SEO tips for PHP hackers and Wordpress users, I’m going to help out the ASP.NET programmers out there still in the dark about SEO problems with their code.  The concept is useful for anyone; but the code is specifically for a function I programmed in VB.NET.

Web application programmers often like to name their files for the function they perform.  For example, you’ve programmed a pretty cool e-commerce app so you name the file shoppingcart.aspx.  Why not?  That’s what it does – it’s a shopping cart.  And without a care in the world you go on programming your shopping cart to create links on your site which look like his: /shoppingcart.aspx?id=4757.  Looks good, right?  It’s a shopping cart page showing a product with an ID of 4757.  It’s just a URL, and you know your customers don’t care what the URLs look like on your site – do they?

Well, they probably don’t.  But search engines do care – and after a while you notice all the clients who bought your shopping cart software are starting to complain that their product pages aren’t getting as much traffic from Google as they’d hoped.  But what if that URL was changed from /shoppingcart.aspx?id=4757 to something like /name-of-my-product.aspx?   Now anyone searching for the “name of my product” keywords might have a better chance of finding your page in Google since the keywords they are searching for are right in the URL of the page.

I’ll show you how to (kind of) easily accomplish this task with ASP.NET, IIS, and some simple URL rewriting in your global.asax file.  This will work in both IIS6 and IIS7, but IIS7 has an add-on module you can download which has another way of providing URL rewrites.  (For more info, check out my earlier post on using the global.asax file to fix canonical URL issues in IIS7 and 7)

I realize these functions are hard to read as inline code in this blog, so you can view all 3 functions in this text file: SEO Search Engine Friendly URL Functions for ASP.NET

First, here’s a function which will take the ID of a product, select the name of the product from a database table, and turn it into a search engine friendly URL.  It will turn /shoppingcart.aspx?id=4757 into /shoppingcart/4757/name-of-my-product.aspx.  You should call this function in your .NET pages where ever you link to product detail pages.

Function: seoPageUrls

Public Function seoPageUrls(ByVal thisProductId As Integer) As String

'### CONNECT TO DATABASE - CHANGE yourDSN
'### IN YOUR WEB.CONFIG FILE ACCORDINGLY
Dim myConnection as New oleDBConnection(ConfigurationManager.AppSettings("yourDSN"))
Dim myCommand as New oleDBCommand
Dim myReader As OleDbDataReader

Dim thisProductName As String = ""

'### GET THE ACTUAL PRODUCT NAME FROM THE DATABASE
myCommand.Connection = myConnection
myCommand.CommandText = "SELECT productName FROM productTable WHERE productId = " & thisProductId

Try
 myConnection.Open()
 thisProductName = myCommand.ExecuteScalar()

Finally
 myConnection.Close()
End Try

myConnection.Dispose()
 
'### GET RID OF NON-FRIENDLY URL CHARACTERS AND REPLACES SPACES WITH DASHES
thisProductName = Regex.Replace(thisProductName, "[^\w\@-]", " ").ToLower()
thisProductName = Regex.Replace(thisProductName.Trim(), "\s{1,}", "-")

'### JUST RETURN THE SEO SEARCH ENGINE FRIENDLY URL
Return "/shoppingcart/" & thisProductId & "/" & thisProductName
 
End Function

 

Now we need a way to tell IIS to rewrite the URLs as visitors (and search engines) request them.  So when someone clicks on a link which looks like /shoppingcart/4757/name-of-my-product.aspx they actually get directed to the page /shoppingcart.aspx?id=4757.  This is done via a technique called URL rewriting in the global.asax file.  The following function will intercept all incoming page requests and send them to the URL rewrite function:

Function: Application_BeginRequest

Sub Application_BeginRequest(ByVal sender as Object, ByVal e as EventArgs)

Try

Dim httpContext As System.Web.HttpContext = httpContext.Current()
Dim currentURL As String = Request.ServerVariables("PATH_INFO")

httpContext.RewritePath(rewriteUrl(currentURL))
 
Catch ex As Exception
 Response.Write("Error in Global.asax:" & ex.Message)
End Try

End Sub

 

You’ll notice it intercepts the incoming URL (contained in the variable currentURL) and sends it to a function called rewriteUrl.  The rewriteUrl function also goes in your global.asax file and it acutally changes the URL requested to one which the web server will understand. 

Function: rewriteUrl

Public Function rewriteUrl(byVal thisURL As String)

Dim currentFileName As String
Dim currentFileType As String
Dim currentFileID As String
Dim returnURL As String

'### THIS REGEX STRING IS LOOKING FOR A URL
'### IN THE FORM: /shoppingcart/4757/name-of-my-product.aspx
'### SO THE URL WILL GET READ LIKE THIS:
'### fileType = shoppingcart
'### identifier = 4757
'### fileName = name-of-my-product.aspx
 
Dim rewrite_regex As Regex = New Regex("^.*/(?<fileType>[^/]+)/(?<identifier>\d+)/(?<fileName>[^/]+)(\?.*)?", RegexOptions.IgnoreCase)
 
Dim match_rewrite As Match = rewrite_regex.Match(thisURL)
 
currentFileType = match_rewrite.Groups("fileType").Value.toString()
currentFileID = match_rewrite.Groups("identifier").Value
currentFileName = match_rewrite.Groups("fileName").Value.toString()

If currentFileID <> "" Then

 '### IF shoppingcart IS THE CURRENT URL, PERFORM THE URL REWRITE
 If currentFileType = "shoppingcart" Then
  returnURL = "/shoppingcart.aspx?id=" & currentFileID
 Else
  '### NO MATCH, NO URL REWRITING - JUST PASS TO REQUESTED URL
  returnURL = thisURL
 End If

Else
 returnURL = thisURL
End If

Return returnURL

End Function
Now go out and bombard the interweb with my self-whoring social links:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • MisterWong
  • StumbleUpon
  • Technorati
  • Diigo
  • FriendFeed
  • Identi.ca
  • LinkedIn
  • PDF
  • Tumblr
  • Twitter
  • Yahoo! Buzz

Tags: .net, asp.net, code sample, IIS, iis6, is7, Search Engine Optimization, seo, url rewrite, vb.net

Similar Posts:

Comments

15 Responses to “SEO Search Engine Friendly URLs with ASP.NET and IIS”

  1. Ruslan Ruslan on November 3rd, 2008 5:19 pm

    If your ASP.NET app is on IIS7 then you could also use the URL rewrite module (http://learn.iis.net/page.aspx/460/using-url-rewrite-module) instead of rewriting in global.asax. The rewrite rule for this would look as below:

    This rule will also handle the URLs that do not have .aspx extension, e.g.
    /shoppingcart/4757/name-of-my-product/

  2. Barry Wise Barry Wise on November 3rd, 2008 7:57 pm

    Ruslan;
    Yeah, I mentioned how to use the IIS7 rewrite module in my other blog post, http://www.barrywise.com/2008/10/seo-canonical-urls-and-301-redirects-in-windows-iis-6-iis-7/

  3. Web Development Company Web Development Company on November 3rd, 2008 9:25 pm

    Before I was just an element with no nothing..But since i’ve read a lot of SEO technique here i am..But, regarding with the URL, your right.. sometimes it hard to understand it..and it takes a lot of time to know it..gotcha..!!

  4. Andy Andy on November 4th, 2008 7:21 pm

    Hey guys i’m looking for feedback on an SEO Tool I’ve been working on, http://spydermate.com any tips or feedback would be appreciated.

  5. Maneet Puri Maneet Puri on November 5th, 2008 3:42 am

    Hey.. Thats a neat one! URLs make a whole lot of difference to the attitude of search engines. Thanks for these pearls of wisdom!

  6. Web Talk Web Talk on November 8th, 2008 1:13 pm

    I would like to reminding, as a side note, that you guys are talking about “search engines” when instead you should talk about Google! In fact, just to cite an example, Yahoo doesn’t even care about the Nofollow tag, Google does and that’s why people are all talking about this in the Internet. As far as URLs are concerned I am not sure if the way they are made really matters to other seach engines such as Yahoo.com and Ask.com.

  7. ASP.Net Programmer ASP.Net Programmer on November 10th, 2008 8:40 pm

    Thanks for this post. I’ve been using URL rewriting for three years and install a similar module to your on all my dynamic site.

    One point to note… ASP.Net Ajax doesn’t like URL rewriting on .Net 2.0. If AJAX is needed on a .Net 2.0 site, you’ll need to write a custom HtmlTextWriter class to format the FORM action attribute appropriately. I imagine that these issues disappear with .Net 3.5 and IIS 7 with the built-in rewriting module and form.action, though I haven’t tested it extensively.

  8. Stu Stu on November 13th, 2008 6:55 pm

    I don’t get the whole Nofollow thing – I mean, people want others to comment on their blog, giving them content, but they’re not prepared to give the commenter something in return. Seems a bit selfish to me

  9. Barry Wise Barry Wise on November 14th, 2008 8:02 am

    @Stu – That’s right, it is selfish … spread the love around!

  10. BitStar Software BitStar Software on November 16th, 2008 4:13 am

    The best solution for this is to write a rewrite module for IIS. The global.asax solutions has some big disadvantages in terms of speed and cpu cost.

    I suggenst you create a http module and link it in web.config:

    public class LangRewrite : IHttpModule
    {
    public void Init(System.Web.HttpApplication Appl)
    {
    //make sure to wire up to BeginRequest
    Appl.BeginRequest += new System.EventHandler(Rewrite_BeginRequest);
    }

    public void Dispose()
    {
    }

    public void Rewrite_BeginRequest(object sender, System.EventArgs args)
    {
    // here you can play with your request in any way you need and when you are done use HttpContext.Current.RewritePath(url) to rewrite the path internaly.
    }
    }

    Then in web.config in httpmodules section add:

    Hope this helped

  11. Barry Wise Barry Wise on November 16th, 2008 8:33 am

    @Bitstar – Ah yes, I can remember IIS modules since the adys of classic ASP and ISAPI. But I wanted something easier and simpler to work with; hence this version.

  12. Inflecto (Software Developers) Inflecto (Software Developers) on February 9th, 2009 8:32 am

    Ditto BitStar on rewriting using a HTTP module. We use this method in our CMS and it works like a charm.

  13. SEO and ASP.NET SEO and ASP.NET on February 20th, 2009 7:22 pm

    As BitStar pointed out, this is more efficiently achieved via an Http Module, however that approach is a lot more involved.

    The whole URL re-writing process is further complicated if you want to preserve your re-written URLs in form post-backs. This involves implementing a form browser in your site – another layer of complication.

    The simplest and most powerful re-writing approach I’ve come accross is ISAPI_Rewrite – an an IIS implementation of Apache’s mod_rewrite that allows for URL re-writing based on regular expressions. Look ma, no code!

  14. Paul Paul on March 29th, 2009 11:39 am

    SEF URLS is uber important for seo!

  15. Site Tool Site Tool on September 4th, 2009 7:20 am

    That’s great, I never thought about SEO Search Engine Friendly URLs with ASP.NET and IIS like that before.

Leave a Reply