Code Samples,Search Engine Optimization

SEO Search Engine Friendly URLs with ASP.NET and IIS

3 Nov , 2008  

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

, , , , , , , , ,


12 Responses

  1. Ruslan says:

    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 says:

    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. Andy says:

    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.

  4. Maneet Puri says:

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

  5. Web Talk says:

    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.

  6. 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.

  7. Stu says:

    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

  8. Barry Wise says:

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

  9. 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

  10. Barry Wise says:

    @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.

  11. Paul says:

    SEF URLS is uber important for seo!

  12. Site Tool says:

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

Comments are closed.

SEO Search Engine Friendly URLs with ASP.NET and IIS

by Barry Wise time to read: 4 min
12