Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET
Tip/Trick

Search engine friendly URLs in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.88/5 (14 votes)
27 Aug 2014GPL34 min read 37.5K   691   21   7
A basic guide for URL Rewriting

Introduction

URL rewriting can be one of the best and quickest ways to improve the usability and search friendliness of your site.

1. What is URL Rewriting?

1. On today’s modern internet, most of the websites are database driven. So, exchange of data between different pages is essential need of database driven websites. The query strings or GET parameters are very good approach to achieve this goal.

http://mayurlohite.com/page.aspx?productID=1

The above URL is dynamic and its sending the product id to page.aspx

2. So, what’s the problem with it?

Well, Maximum search engines (some exceptions – like Google) will not index any pages that have a question mark or other character (like an ampersand or equals sign) in the URL. So that means the page with question marks in URL is ignored by most of the search engines.

3. So, How search engine finds or index my page ?

There will be a solution of this problem, which is rewrite the URL to search engine friendly URL.

4. What is exactly the search engine friendly URL?

Lets take a look at below URL –

http://mayurlohite.com/page.aspx?productID=1 &Productnane=visual-studio

We have to convert above URL to following URL.

http://mayurlohite.com/displayproduct/1/visual-studio

Clearly a much cleaner and shorter URL. It’s much easier to remember, and vastly easier to read out. That said, it doesn’t exactly tell anyone what it refers.

5. How to convert Non search friendly URL to search friendly URL?
Its an easy task to converting URLs. Actually, I am working with ASP.NET C#. So, I will explaining how to achieve this with ASP.NET. I am using Global.axas Application_BeginRequest event handler.
Application_BeginRequest: is an event handler. It is part of the ASP.NET website system. The Application_BeginRequest method is executed on all requests handled by the ASP.NET run time.
First, this event handler is declared in a class that derives from HttpApplication. In such classes, the Application_BeginRequest method is automatically used when a request is received.

Using the code

1. First we are creating new website in visual studio 2010 for that open visual studio 2010. Click on File -> New -> Website

2. Select Visual C# from left and click on ASP.NET Empty Website template. In Bottom Web location Select File System and Type path to create new website.Give name “URLRewriteDemo” to website.

3. Now empty asp.net website is created there is nothing to display on solution so first we create Default.aspx page. To create new page right click on solution explorer click Add New Item. Select Webform from template and name it Default.aspx and click on add.

4. Add one new page to solution(same as Default.aspx) and name it page.aspx.

5. Now we want to send the Product ID and Product Name from Default.aspx to page.aspx So, We are using Query String to pass the values e.g. http://mayurlohite.com/page.aspx?productid=1&productname=visual-studio

6. we can access these values on page.aspx by Request.QueryString["productid"] and Request.QueryString["productname"] but this is not a SEO friendly pattern.

7. To solve this Add one Hyperlink field to Default.aspx and set NavigateUrl=”~/displayproduct/1/visual-studio”.

ASPX CODE FOR Default.aspx

ASP.NET
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> URL Rewrite Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center;">
        <h1>
            URL Rewrite Demo</h1>
    </div>
    <br />
    <div style="text-align: center;">
        <h2>
            <asp:HyperLink ID="URLHyperLink" runat="server" NavigateUrl="~/displayproduct/1/visual-studio">URL Rewrite</asp:HyperLink>
        </h2>
    </div>
    </form>
</body>
</html> 

ASPX CODE FOR page.aspx  

ASP.NET
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>URL Rewrite Demo</title>
</head>
<body>
    <form id="form1″" runat="server">
    <div style="text-align: center;">
        <h1>
            URL Rewrite Demo</h1>
    </div>
    <br />
    <div style="width: 500px; margin: 0 auto;">
        <table style="width: 100%;">
            <tr>
                <td>
                    &nbsp;
                    <asp:Label ID="Label1″" runat="server" Text="Product ID:"></asp:Label>
                </td>
                <td>
                    &nbsp;
                    <asp:Label ID="ProductLabel" runat="server"></asp:Label>
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;
                    <asp:Label ID="Label2″" runat="server" Text="Product Name:"></asp:Label>
                </td>
                <td>
                    &nbsp;
                    <asp:Label ID="ProductNameLabel" runat="server"></asp:Label>
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;
                </td>
                <td>
                    &nbsp;
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

8. In this example we are passing “displayproduct/1/visual-studio” to hyperlink[navigateurl] which is SEO friendly URL.

9. To write our rewrite rule we have to add Global.asax file in project. To add Global.asax right click on solution and click Add New Item and select “Global Application Class” from templates.

10. We are creating new Event Handler in Global.asax name it protected void Application_BeginRequest(Object sender, EventArgs e){}

CODE FOR GLOBAL.ASAX

C#
<script runat="server">

void Application_Start(object sender, EventArgs e)
 {
    // Code that runs on application startup
 }

void Application_End(object sender, EventArgs e)
 {
    // Code that runs on application shutdown  
 }

 void Application_Error(object sender, EventArgs e)
 {
    // Code that runs when an unhandled error occurs  
 }

 void Session_Start(object sender, EventArgs e)
 {
    // Code that runs when a new session is started  
 }  

 void Session_End(object sender, EventArgs e)
 {

    // Code that runs when a session ends.
    // Note: The Session_End event is raised only when the sessionstate mode
    // is set to InProc in the Web.config file. If session mode is set to StateServer
    // or SQLServer, the event is not raised.  
 } 
 
 protected void Application_BeginRequest(Object sender, EventArgs e)
 {
    //Grab the URL for matching the pattern. Returns the current URL path.
    //e.g. http://example.com/displayproduct/1/visual-studio
    
    HttpContext incoming = HttpContext.Current;
    string oldpath = incoming.Request.Path.ToLower();

    //Declare variables for Query Strings.

    string productid = string.Empty;
    string productname = string.Empty;

    // Regular expressions to grab the productid and productname from the page.aspx
    //Here I am using regular expression to match tghe pattern.

    Regex regex = new Regex(@"displayproduct/(\d+)/(.+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
    MatchCollection matches = regex.Matches(oldpath);  
    
    //If Matches found then Grab the product id and name and rewrite it as our typical query string format.
    //e.g: http://example.com/page.aspx?productid=1&productname=visual-studio

    if (matches.Count > 0)
    {

     productid = matches[0].Groups[1].ToString();
     productname = matches[0].Groups[2].ToString();
     incoming.RewritePath(String.Concat("~/page.aspx?productid=", productid, "&productname=", productname ), false);
    }

 } 
 </script>

11. Now we are analyzing Application_BeginRequest(Object sender, EventArgs e) event handler.

A. The first two lines returns the current URL path.

C#
HttpContext incoming = HttpContext.Current;
string oldpath = incoming.Request.Path.ToLower();

B. By using regular expression we can match the pattern of our requested URL with our rewrite URL. Means, when http://example.com/displayproduct/1/visual-studio is pattern matched with our regular expression and it rewrite the path to http://example.com/productid=1&productname=visual-studio

12. We can access the both query string parameter as same previous. e.g. Request.QueryString["productid"] and Request.QueryString["productname"] there is no change in traditional ASP.NET Query String system.

Hence, we achieve the SEO friendly URL by Global.asax Rewrite rule.

Points of Interest

Converting your traditional query strings to Search Engine Friendly URL behavior which gives tremendous benefits for search engine optimization also urls are easy to memorize.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Web Developer
India India
My name is Mayur Lohite. I am Programmer and Web Developer also I am Interested in Web Application Security and penetration. From a young age I’ve been fascinated with building web application and breaking it. So I have choose the Information technology as my career and completed the Degree in Information technology.

I’m a interested in operating and design of large-scale web applications/infrastructure and I’m interested in web application security also I am interested in some networking setting up servers, domains experimenting with clouds(well I am not professional at it)

I am a big fan of Anime series (Naruto) and also love to playing games. In the mean time I love to watching movies specially action movies.

Now I’m a white hat penetration tester. bug hunter and all out security freak by profession and passion. I’ve listed many websites Hall of fame e.g. Microsoft, Yahoo, Apple, Adobe

Comments and Discussions

 
Questionhave some question in Url Rewritting Pin
Samatha Reddy G26-Sep-14 1:48
Samatha Reddy G26-Sep-14 1:48 
AnswerRe: have some question in Url Rewritting Pin
Mayur V Lohite19-Oct-14 19:59
professionalMayur V Lohite19-Oct-14 19:59 
QuestionYup Pin
Duane Urban2-Sep-14 14:00
Duane Urban2-Sep-14 14:00 
SuggestionAnother Version Pin
adriancs27-Aug-14 21:28
mvaadriancs27-Aug-14 21:28 
AnswerRe: Another Version Pin
Mayur V Lohite27-Aug-14 22:25
professionalMayur V Lohite27-Aug-14 22:25 
yes routing is great and powerful features But I think its available for 3.5 SP1 and later framework for below 3.5 SP1 framework users can use this technique.
Thank You.
Regards,
Mayur Lohite
http://mayurlohite.com

GeneralMy vote of 5 Pin
Pratik Bhuva27-Aug-14 20:11
professionalPratik Bhuva27-Aug-14 20:11 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun27-Aug-14 18:17
Humayun Kabir Mamun27-Aug-14 18:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.