articles

Home / DeveloperSection / Articles / URL rewriting in asp.net

URL rewriting in asp.net

Anchal Kesharwani7733 25-Jun-2014

In this article describe the concept of URL rewriting in asp.net. URL is most necessary part of any website. Here we understand the URL rewriting with the help of simple examples.

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL. URL rewriting is short the url of website, secure, easy to type.

If you do not rewrite in this type of website hacker hack your website. In the above website they shows the produst.aspx and also show the category of product. In this case any user can access restricted data or access all these things which is not allowed because he finds the address or pages where to redirect.

Why does URL mapping and rewriting matter?

1) 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.
2) Improving the search relevancy of pages on your site with search engines like Google, Yahoo and Live.  Specifically, URL Rewriting can often make it easier to embed common keywords into the URLs of the pages on your sites, which can often increase the chance of someone clicking your link.  Moving from using querystring arguments to instead use fully qualified URL's can also in some cases increase your priority in search engine results.  Using techniques that force referring links to use the same case and URL entrypoint (for example: mysite.com/articles instead of mysite.com/articles/default.aspx) can also avoid diluting your page rank across multiple URLs, and increase your search results.

Sample URL rewriting

I'm going to assume we are building a set of e-commerce catalog pages within an application, and that the products are organized by categories (for example: TV, FRIDGE, AC, etc).

Let's assume that we initially have a page called "ItemCollection.aspx" that takes a category name as a querystring argument, and filters the products accordingly.  The corresponding URLs to this Products.aspx page look like this:

http://www. shopping.com/ItemCollection.aspx?category=TV

http://www. shopping.com/ItemCollection.aspx?category=FRIDGE

http://www. shopping.com/ItemCollection.aspx?category=AC

http://www. shopping.com/ ItemCollection.aspx?category=MICROWAVE

 

Rather than use a querystring to expose each category, we want to modify the application so that each product category looks like a unique URL to a search engine, and has the category keyword embedded in the actual URL (and not as a querystring argument).  We'll spend the rest of this blog post going over 4 different approaches that we could take to achieve this.

URL rewriting has many approaches to rewrite the url:

Use Request.PathInfo Parameters Instead of QueryStrings


To help explain the usefulness of this property, consider the below URL scenario for our e-commerce store:

http://www. shopping.com/ItemCollection.aspx/TV

http://www. shopping.com/ItemCollection.aspx /FRIDGE

http://www. shopping.com/ItemCollection.aspx / AC

http://www. shopping.com/ ItemCollection.aspx /MICROWAVE

 

In the above examples, URLs have no longer querystring values, instaed the category value appended on  page ItemCollection.aspx. In automated search engine crawler will then interpret these URLs as three different URLs, and not as one URL with three different input values (search engines ignore the filename extension and just treat it as another character within the URL).

In the ASP.NET Request.PropertyInfo is a proprty that we used in url rewriting caseSimply use the Request.PathInfo property, which will return the content immediately following the products.aspx portion of the URL. So for the above URLs, Request.PathInfo would return "/TV", "/FRIDGE", and "/AC" (in case you are wondering, the Request.Path property would return ItemCollection.aspx").

Using an HttpModule to Perform URL Rewriting

An alternative approach to the above Request.PathInfo technique would be to take advantage of the HttpContext.RewritePath() method that ASP.NET provides.  This method allows a developer to dynamically rewrite the processing path of an incoming URL, and for ASP.NET to then continue executing the request using the newly re-written path.

This looks to the outside world like there are three separate pages on the site (and will look great to a search crawler).  By using the HttpContext.RewritePath() method we can dynamically re-write the incoming URLs when they first reach the server to instead call a single ItemCollection.aspx page that takes the category name as a Querystring or PathInfo parameter instead.  For example, we could use an Application_BeginRequest event in Global.asax like so to do this:

void Application_Start(object sender, EventArgs e)

        {

 

            //string fullOrigionalpath = Request.Url.ToString();

            string orginalPath = HttpContext.Current.Request.Path.ToLower();

 

            if (orginalPath.Contains("/TV.aspx"))

            {

               // orginalPath.Replace("/ItemCollection.aspx?Category=TV");

                Context.RewritePath(orginalPath.Replace("/TV.aspx","/ItemCollection.aspx?Category=TV"));

            }

            else if (orginalPath.Contains("/AC.aspx"))

            {

                Context.RewritePath(orginalPath.Replace("/AC.aspx","/ItemCollection.aspx?Category=AC"));

            }

 

        }

 

This work perform by the help of HttpModule. In the following example give code

for web.config file.

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

  <rewriter>

    <rewrite url="~/ItemCollection/AC.aspx" to="~/ItemCollection.aspx?category=AC" />

    <rewrite url="~/ItemCollection/TV.aspx" to="~/ItemCollection.aspx?category=TV" />

  </rewriter>

  </configuration>

 

HttpModule url rewriting also supports the regular expression.

<rewriter>

    <rewrite url="~/ItemCollection/(.+).aspx" to="~/ItemCollection.aspx?category=$1" /> </rewriter>

 
Using an HttpModule to Perform Extension-Less URL Rewriting with IIS7


The above HttpModule approach works great for scenarios where the URL you are re-writing has a .aspx extension, or another file extension that is configured to be processed by ASP.NET.  When you do this no custom server configuration is required - you can just copy your web application up to a remote server and it will work fine.

http://www. shopping.com/ItemCollection/TV

http://www. shopping.com/ItemCollection/FRIDGE

http://www. shopping.com/ItemCollection/AC

http://www. shopping.com/ ItemCollection/MICROWAVE

 

With IIS5 and IIS6, processing the above URLs using ASP.NET is not super easy.  IIS 5/6 makes it hard to perform URL rewriting on these types of URLs within ISAPI Extensions (which is how ASP.NET is implemented). Instead you need to perform the rewriting earlier in the IIS request pipeline using an ISAPI Filter. I'll show how to-do this on IIS5/6 in the Approach 4 section below.

The good news, though, is that IIS 7.0 makes handling these types of scenarios super easy.  You can now have an HttpModule execute anywhere within the IIS request pipeline - which means you can use the URLRewriter module above to process and rewrite extension-less URLs (or even URLs with a .asp, .php, or .jsp extension).  Below is how you would configure this with IIS7:

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

  <rewriter>

    <rewrite url="~/ItemCollection/(.+).aspx" to="~/ItemCollection.aspx?category=$1" />

  </rewriter>

  <system.webServer>

    <modules runAllManagedModulesForAllRequests="true">

      <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />

    </modules>

    <validation validateIntegratedModeConfiguration="false" />

  </system.webServer>

</configuration> 

1) It will work on any IIS 7.0 machine.  You don't need an administrator to enable anything on the remote host.  It will also work in medium trust shared hosting scenarios.

2) Because I've configured the UrlRewriter in both the <httpModules> and IIS7 <modules> section, I can use the same URL Rewriting rules for both the built-in VS web-server (aka Cassini) as well as on IIS7.  Both fully support extension-less URLRewriting.  This makes testing and development really easy.

IIS 7.0 server will ship later this year as part of Windows Longhorn Server, and will support a go-live license with the Beta3 release in a few weeks.  Because of all the new hosting features that have been added to IIS7, we expect hosters to start aggressively offering IIS7 accounts relatively quickly - which means you should be able to start to take advantage of the above extension-less rewriting support soon.  We'll also be shipping a Microsoft supported URL-Rewriting module in the IIS7 RTM timeframe that will be available for free as well that you'll be able to use on IIS7, and which will provide nice support for advanced re-writing scenarios for all content on your web-server.


Updated 13-Aug-2018

Leave Comment

Comments

Liked By