Pages

Wednesday, August 3, 2011

All about URL Rewriting and 301 permanent Redirection



Introduction:

You must be having URL's in your website like below:
http://yoursite.com/info/dispEmployeeInfo.aspx?EmpID=459-099&type=summary 
Don't say me NO... ok!  you should be having them ...  ;)


In the same way...  my Customer also want us to mask the actual URL ta make  them more readable (sucurable), and should be in a way to memorize very easily.


So, I have searched couple of websites, and found a procedure, but it turned to work only in IIS 6, where as our Client's environment is IIS 7 :( ... 
so, my search started again, and finally found it :)  and I would like to explain and share the procedure, hope you find it useful! 
here we go...




Why URL Rewrite?

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource.
With the URL Rewriting, you can change the above said URL to look like:
http://yoursite.com/people/sales/chuck.smith


Indirectly, with this procedure, you can also redirect the pages that no longer exists to the new one.


Moreover, this helps to improve the search relevancy of pages on your site with search engines like Google, Yahoo. 


Now, I will explain how easily, this can be done


How URL Rewrite works?


The IIS receives the request made by the client and dispatches it to aspnet_isapi.dll. Next, the ASP.NET engine initializes the configured HTTP modules. Finally, the proper HTTP handler is invoked and the requested resource is rendered, returning the generated markup back to IIS and back to the requesting client.


Here the custom module (Intelligencia.UrlRewriter) is used and when the URL request (http://abcd.com/LazyBubble/SecondPage) is made, the request reaches the IIS of the Server and the URL Rewrite is done based on the url mapping configured in the ‘Configuration file’, with the help of HTTP Module and HTTP Handler.




Steps:


1. Firstly, Download the code from here

2. Pick up the Intelligencia.UrlRewriter.dll from the the dowloaded code location - UrlRewrite_HttpModule\bin and add it to your Web Project.   


3. Add the following sections to your web.config file.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  
<configSections>
    
<section name="rewriter" requirePermission="false" 

type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
  </configSections>

  
<system.web>    
    
<httpModules>
      
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, 
Intelligencia.UrlRewriter" />
    </httpModules>  
  
</system.web>

  
<system.webServer>
    
<modules runAllManagedModulesForAllRequests="true">
      
<add name="UrlRewriter" 

            type="Intelligencia.UrlRewriter.RewriterHttpModule"/>
    </
modules>
    
<validation validateIntegratedModeConfiguration="false" />
  </
system.webServer>

  
<rewriter>
    
<rewrite url="SecondPage" to="Page2.aspx" />
  </
rewriter>

  </configuration>




4. Add the Form.Browser and Form Rewriter.vb from the above Code downloaded.




The problem when using URL-Rewriting is that the URL that the <form> control renders is not the original URL of the request (for example: /products/books), but rather the re-written one (for example: /products.aspx?category=books).  This means that when you do a postback to the server, the URL will not be your nice clean one.
  
Specifically, you can take advantage of the new ASP.NET 2.0 Control Adapter extensibility architecture to customize the rendering of the <form> control, and override its "action" attribute value with a value you provide.  


This doesn't require you to change any code in your .aspx pages


Instead, just add a .browser file to your /app_browsers folder that registers a Control Adapter class to use to output the new "action" attribute.


For the VB code to run in C#, add th below section in your web.config file.



 <compilation debug="false">
      <codeSubDirectories>
        <add directoryName="VBCode"/> 
      </codeSubDirectories>


</compilation>



5.  Create a new ASP.Net website and add 2 Pages naming them as Page1.aspx & Page2.aspx
     Add the below code in those 2 pages.


Page1.aspx


<form id="form1" runat="server">
    <div>
        <asp:Button ID="btnRedirect" runat="server" Text="Redirect to Page2" onclick="btnRedirect_Click" />
    </div>
</form>

Page1.aspx.cs

protected void btnRedirect_Click(object sender, EventArgs e)
    {
        Response.Redirect("SecondPage", false);
    }


Page2.aspx

<form id="form1" runat="server">
    <div>
        <h1>
        This is Page 2
        </h1>
    </div>
</form>

In web.config

<rewrite url="SecondPage" to="Page2.aspx" />


Build the Project and Run it. Browse the Page1.aspx

Click the Button on the Page.









It redirects to Page2.aspx. If you notice, the URL - http://localhost:3232/LazyBubble/SecondPage

"SecondPage" is the custom name which we defined in the web.config file, under the <rewriter> section.


In this way, you can redirect to the custom named files (SecondPage) hiding the actual Page name files (Page2.aspx).



Troubleshooting:


1. CSS/Images not working:
    This is because you might have relative References to these files within  
    their HTML pages - and  when you start  to re-write URLs within an 
    application you need to be aware that the browser will often be requesting 
    files in different logical hierarchy levels than what is really stored on the  
    server.


    For example, if our /products.aspx page above had a relative reference to 
    "logo.jpg" in the .aspx page, but was requested via the products/books.aspx   
    url, then the browser will send a request for /products/logo.jpg instead of 
    /logo.jpg when it renders the page.  To reference this file correctly, make  
    sure you root qualify CSS and Image references ("/style.css" instead of 
    "style.css").  
    For ASP.NET controls, you can also use the ~ syntax to reference files from 
    the root of the 
    application (for 
    example: <asp:image imageurl="~/images/logo.jpg" runat="server"/>. 
    The ~ will not work for HTML image control, so you have to use the ASP.Net 
    Image controls.


2. Reference to js file - not working
    Please take care in referencing the js files in the page. Probable you may 
    have follow this :
    <script type="text/javascript" src="../../../ui/ui.core.js"></script>


3.  Error - Cannot use a leading .. to exit above the top directory


   When you use relative paths incorrectly.  If you generate a url with too many 
   “../../../” levels in it that would take the user above the root directory, you 
   can generate the exception.


   If you are using Server.Transfer or HttpContext.RewritePath to redirect a 
   request (say map it to a template page) and have a HyperLink control with 
   the ImageUrl property set, you win an extra “../” by the framework.  The fix 
   is to wrap the HyperLink control around an Image control. 


   In code, if you have,
<asp:HyperLink ID="hlnkTripImages" runat="server" ImageUrl="~/images/camera_icon.gif"></asp:HyperLink>

change it to,
<asp:HyperLink ID="hlnkTripImages" runat="server">

    <asp:Image runat="server" ID="imgTripImages" 
         ImageUrl="~/images/camera_icon.gif" ToolTip="Photo"/>
</asp:HyperLink>




301 Permanent Redirection

301 Redirection is the technique of permanently redirecting the old (obsolete) URL to the provided new URL. These links might be from other sites that have not realized that there is a change or from bookmarks/favourites that users have saved in their browsers.
This redirection can be achieved in one of the following 2 ways:
1.      Creation of the aspx pages for all the old URLs
2.      Configuration of OLD & New URLs in the web.config file using Intelligencia.URLRewriter dll


1.     Configuration of OLD & New URLs in the web.config file.

In this approach, individual aspx page is created for every old URL.
For example, if the old URL is http://www.mahindrahomestays.com/Pages/home.aspx which needs to be redirected to the new URL - http://www.mahindrahomestays.com/homepage.aspx, thenhome.aspxfile would be created under the “Pages” folder with the below script which handles the 301 Redirection.

<script language="c#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.mahindrahomestays.com/homepage.aspx");
}
</script>
Drawback:
The drawback for this approach is, if we have 100+ URL’s, we will end up in creating 100+ files which leads to waste of memory in the Server.


2.     Configuration of OLD & New URLs in the web.config file using Intelligencia.URLRewriter dll

Using the Intelligencia.UrlRewriter.dll, the permanent redirection can be achieved very easily, by just writing the in the web.config.
For example,
<rewriter>                                                                <redirect url = "^~/Pages/home.aspx" to = "~/homepage.aspx" permanent="true" /></rewriter>

4 comments:

  1. nice one... intersting part is the reference section :) ... none the less, good effort and will visit it back when my project wants this :D

    ReplyDelete
  2. @dipdawiz.. u know me right... I am always honest..! :) LOL

    ReplyDelete