Tuesday, September 30, 2014

How to Rewrite URL in Asp.Net (Search Engine Friendly Url)

Here is a simple way to Rewrite URLs in Asp.net Using Global.asax file.

Here I presenting an important aspect Search Engine optimization technique. URL rewriting can be one of the best and quickest ways to improve the usability and search friendliness of your site.

Handling cases where you want to restructure the pages within your web application, and you want to ensure that people who have bookmarked old URLs don't break when you move pages around. Url-rewriting enables you to transparently forward requests to the new page location without breaking browsers.

Normal URL: http://site.com/Default2.aspx?Coursename=Asp.net&CourseID=12
SEO friendly URL :http://site.com/IT-Training/Asp.net/12


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.

Its an easy task to converting URLs. Actually, I am working with ASP.NET C#. So, I will explaining how to achive this with ASP.NET. I am using Global.asax 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 runtime.
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.

Now Lets Start Doing

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

Step2:  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 “Site” to website.



Step3: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.

Step4 :Add one new page to solution and name it Default2.aspx.

Step5 :Now we want to send the Coursename and CourseID from Default.aspx to Default2.aspx So, We are using Query String to pass the values  e.g. http://site.com/Default2.aspx?Coursename =Asp.net/&CourseID =12

Step6 :we can access these values on Default2.aspx by Request.QueryString["Coursename "] and Request.QueryString["CourseID "] but this is not a SEO friendly pattern.

Step7 : To solve this create menu with list of Courses to Default.aspx and set NavigateUrl=”~/IT-Training/Asp.net/12 to each menu item likewise set NavigateUrls to remaimng items in menu.

Below Screen will show the screen Shot of Default.aspx with list of coureses


















As you observe above screen shot i have written CSharpDotNet behalf of C#.Net because the SEO does not supports dot(.),Hash(#),Spaces( ). If you want spaces between words you should use iphen(-) as i have use in above screen shot .Net-Online-Training-Courses.

Now our goal is if we to see  any of course from menu  Suppose if you click last item it should redirect and URL should be seo friendly url as show below

Normal URL : http://site.com/Default2.aspx?Coursename=.Net-Online-Training-Courses&CourseID=22
SEO friendly URL : http://site.com/IT-Training/.Net-Online-Training-Courses/22

Step 8:  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.






















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

In that event add following code as shown below

 protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        //Get the URL for matching the pattern. Returns the current URL path.
        //e.g. http://site.com/IT-Training/.Net-Online-Training-Courses/22
        HttpContext incoming = HttpContext.Current;
        string oldpath = incoming.Request.Path;

        //Declare variables for Query Strings.
        string coursename = string.Empty;
        string couserid = string.Empty;
        

        // Regular expressions to grab the coursename and couserid to the Default2.aspx because it takes Coursename and CourseID
        //Here I am using regular expression to match the pattern.
        Regex regex = new Regex(@"IT-Training/(.+)/(\d+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
        MatchCollection matches = regex.Matches(oldpath);

         //If Matches found then Grab the Coursename  and CourseID and rewrite it as our typical query string format.
        //e.g: http://site.com/Default2.aspx?Coursename =.Net-Online-Training-Courses&CourseID=22
        if (matches.Count > 0)
        {
            coursename = matches[0].Groups[1].ToString();
            couserid = matches[0].Groups[2].ToString();
            incoming.RewritePath(String.Concat("~/Default2.aspx?coursename=", coursename, "&couserid=", couserid), false);
        }
        
    }  

  1. The first two lines returns the current URL path.HttpContext incoming = HttpContext.Current;string oldpath = incoming.Request.Path.ToLower();
  2. By using regular expression we can match the pattern of our requested URL with our rewrite URL. Means, when http://site.com/IT-Training/.Net-Online-Training-Courses/22 is pattern matched with our regular expression and it rewrite the path to http://site.com/Default2.aspx?coursename =.Net-Online-Training-Courses&couserid =22
After finishing Global.asax writting complie and execute and click any one of course from Default1.aspx we get following output.


By This we can get SEO frendly URL








No comments:

Post a Comment