How to implement and use URL rewriting in ASP. NET)

Source: Internet
Author: User
Flexible URL rewriting can increase the availability and professionalism of your website. This is also an important factor in helping websites better be indexed by search engines. In this article Article In, I will show you how to easily implement URL rewriting in ASP. NET, as well as some common solutions. I will also explain why URL rewriting is so important and how to use it to enhance your website.

What is URL rewriting?

URL rewriting is the process of first obtaining an access URL request and then re-writing it into another URL that the website can process. For example, if the URL in the browser is "www.mysite.com/userprofile/1.aspx.pdf", then the URL can be rewritten as "www.mysite.com/userprofile.aspx? Such a URL can be better read by the website.

URL rewriting is a very useful feature because it enables you to improve the search engine's ability to read and index your website. After you change your website structure, users do not need to modify their bookmarks, but do not need other websites to modify their links; it can also improve the security of your website; it also makes your website easier to use and more professional. I will explain in detail how to use URL rewriting in this article.

How to rewrite a URL

URL rewriting can be achieved through programming. The contex. rewritepath () method in ASP. NET allows youProgramTo rewrite the request URL. After rewriting, the system will use the new path to continue executing this request.

In the application_beginrequest () method of the global. asax file, you need to addCodeAnd then rewrite the rules based on one or more URLs to form the path to be further processed. The following example executes the following URL rewriting rules:

Code List 1: URL rewriting using contex. rewritepath ()

 void application_beginrequest (Object sender, eventargs E) 
{< br> string Path = request. URL. tostring ();
If (RegEx. ismatch (path, "/urlrewriting/oldurl. aspx ",
regexoptions. ignorecase)
{< br> context. rewritepath ("/urlrewriting/newurl. aspx ");
}< br> else if (RegEx. ismatch (path, "/urlrewriting/useraccount /(. + ). aspx ",
regexoptions. ignorecase)
{< br> string idstring =
path. substring (path. lastindexof ('/') + 1,
path. length-path. lastindexof ('/')-6);
context. rewritepath ("/urlrewriting/useraccount. aspx? Id = "+
idstring);
}< BR >}< br>

In this example, each time a new request is processed, it will first view this application_beginrequest (). By using request. URL attribute to obtain the entered URL path, and then apply the website URL rewriting rule using a regular expression. After matching the expected URL, rewrite them to the desired URL.

 

Use urlrewriting. Net to implement more powerful URL rewriting

When the rewrite rules are relatively simple and small, use context. the rewritepath () method does a good job of rewriting URLs programmatically, but some large websites usually have many URL rewriting rules. Manual programming of all these rewrite rules may be a troublesome and error-prone method.

A better solution is to use an httpmodule in the web. config file to dynamically process URL rewriting rules. Even more pleased, you don't have to write httpmodule on your own to handle these tasks. There are already several very good free versions for you to use. Which of the following are: urlrewriting. net,
Urlrewriter. net, rewrite. net.

In this article, I will use urlrewriting. Net to demonstrate a simple example. Before using urlrewriting. net, download it from the urlrewriting. Net website and put it in the/bin folder of your website.

Next, add the following configuration to your web. config file:

Code List 2: configuration added to Web. config

<Configsections>
<Section name = "urlrewritingnet" requirepermission = "false"
Type = "urlrewritingnet. configuration. urlrewritesection,
Urlrewritingnet. urlrewriter "/>
</Configsections>
<System. Web>
<Compilation DEBUG = "true"/>
<Authentication mode = "Windows"/>
<Httpmodules>
<Add name = "urlrewritemodule"
Type = "urlrewritingnet. Web. urlrewritemodule,
Urlrewritingnet. urlrewriter "/>
</Httpmodules>
</System. Web>

Now, in the web. config file, you can add the following code and enter your own URL rewriting rules. It will implement the following URL rewriting rules:

Code List 3: Configure Rewrite Rules for urlrewriting. net

<Urlrewritingnet
Rewriteonlyvirtualurls = "true"
Contextitemsprefix = "querystring"
Defaultpage = "default. aspx"
Defaultprovider = "RegEx"
Xmlns = "http://www.urlrewriting.net/schemas/config/2006/07">
<Rewrites>
<Add name = "useraccount"
Virtualurl = "^ ~ /Useraccountv2/(. +). aspx"
Rewriteurlparameter = "excludefromclientquerystring"
Destinationurl = "~ /Useraccountv2.aspx? Id = $1"
Ignorecase = "true"/>
<Add name = "movies_action"
Virtualurl = "^ ~ /Movies/action. aspx"
Rewriteurlparameter = "excludefromclientquerystring"
Destinationurl = "~ /Movies. aspx? Movietype = action"
Ignorecase = "true"/>
<Add name = "movies_drama"
Virtualurl = "^ ~ /Movies/drama. aspx"
Rewriteurlparameter = "excludefromclientquerystring"
Destinationurl = "~ /Movies. aspx? Movietype = drama"
Ignorecase = "true"/>
<Add name = "movies_comedy"
Virtualurl = "^ ~ /Movies/comedy. aspx"
Rewriteurlparameter = "excludefromclientquerystring"
Destinationurl = "~ /Movies. aspx? Movietype = comedy"
Ignorecase = "true"/>
</Rewrites>
</Urlrewritingnet>

As shown above, when using a URL similar to urlrewriting. net httpmodule, you can simply insert your website rewrite rules to the Web one by one. config file without writing any code. In this way, regardless of the size of your website, managing these URL rewriting rules becomes very easy.

Although the example here is very simple, urlrewriting. Net is a powerful program with many options that I have not used here. Complete documentation and sample applications can be viewed from the urlrewriting official website.

 

Process the response data (PostBack)

When the URL rewriting method is used in ASP. NET, it often raises a potential problem: when a page is sent back to the server, the original clean input URL is usually not saved. For example, you can use /Movies/action. aspx and other simple URLs enter a URL, but when you click a button to send data back to the server, the URL will be changed back to the actual URL -- "~ /Movies. aspx? Movietype = action ".

The root cause of the problem is the <form runat = "server"> label action attribute, which uses a real URL instead of the entered URL.

An easy way to solve this problem is to implement your own form tag version by extending the existing form tag. Then you can set the action as the input URL instead of the rewritten URL. See the following example:

Code list 4: custom form tags can process URL-rewriting data delivery

 Public class rewriteform: htmlform {

Protected override void
Renderattributes (system. Web. UI. htmltextwriter writer ){

// Name
Writer. writeattribute ("name", this. Name );
Base. Attributes. Remove ("name ");

// Method
Writer. writeattribute ("method", this. method );
Base. Attributes. Remove ("method ");

This. Attributes. Render (writer );

// Action
String action = context. Request. rawurl;

If (action! = NULL ){
Writer. writeattribute ("action", action );
}
Base. Attributes. Remove ("action ");

// ID
If (base. ID! = NULL ){
Writer. writeattribute ("ID", base. clientid );
}
}
}

With the above code, you can now use the <mytags: rewriteform id = "form1" runat = "server"> tag, instead of using the standard <Form ID = "form1" runat = "server"> tag, the URL remains unchanged even during data delivery.

 

Process links and image/CSS URLs

When using URL rewriting, it is important to note that the relative links, images, and CSS on the rewritten page may not be displayed normally, because the relative reference will be the input URL and the actual URL from time to time.

For example, if the home page of a website is "/home. aspx? Lang?en=, with a relative address of "sitmysitelogo.jpg", but this page is "/en/home. the aspx "URL request has a"/enable directory to display the user's desired English page, and the relative link of "mysitelogo.jpg" is changed to "/en/mysitelogo.jpg". Of course this is incorrect, therefore, this image will not be correctly displayed.

To ensure that the image and link point to the correct URL, please specify an absolute path, such as "/mysitelogo.jpg" or "www.mysite.com/mysitelogo.jpg.pdf ". Another option is to use "~ /", That is," ~ /Mysitelogo.jpg ". This will automatically display the correct path of your file or link.

Modify file extension

Another more interesting modification you can make to your site is to modify the extension of your page. For example, some users want to modify the ". aspx" extension to a specific extension, such as ". X" or ". mysite", or even ". jsp" or ". php ". This is because of security considerations, or simply to increase the aesthetics of your website.

To modify the extension of your website page, you only need to use the method in the above URL rewriting example to rewrite the URL containing ". mysite" to a ". aspx" URL. If you use modules such as urlrewriting. net, implementing this change is even easier. You only need to add an rewrite rule at the end of the rewrite rule. For example, rewrite "~ /(. +). Mysite "is" ~ /(. +). Aspx ". Because URL rewriting rules are executed in order, placing this rule at the end will capture all pages.

Note that when a specific file extension is used, you must configure the new extension in the IIS ing. All extensions related to ASP. NET (". aspx", ". asax", ". config", and ". cs") are mapped to ISAPI extensions of aspnet_isapi.dll. Add your new extension to the same configuration.

How to Use URL rewriting

You have spent a lot of time learning how to rewrite a URL. Now you need to take a look at how to use this function to improve your website.

1. Improve the search engine's ability to read and index your website

Search engines crawl and index websites based on URLs. Many dynamic database-driven websites have dynamic URLs with URL parameters, such as "www.mysite.com/userprofile.aspx? The ID parameter in ID = 1. The search engine cannot completely index your website. By modifying the URL to form a category like "www.mysite.com/userprofile/1.aspx.pdf", you can help search the engine more easily to access your website.

The search engine usually uses keywords in your url to determine the relevance of Your webpage. Sometimes, you may want to modify the URL to better reflect the webpage content without modifying the website directory architecture.

Although your website is better indexed by search engines, although there is no good alternative or fast-paced method, you can understand how search engines work and then optimize your website based on it, it may bring unexpected results.

2. Modify the website structure without requiring users to modify their bookmarks, or requiring other websites to change the links that direct to your website.

If you want to modify the name of a web page or modify the folder structure of the stored web page, it will bring confusion to those who have already collected your web page and some websites for your links. A feasible solution is to use URL rewriting to transparently redirect users to the correct webpage.

For example, if you have.

3. Improve Website Security

Websites can provide some clues for hackers to attack because they usually expose the internal working mechanism of your website.

For example, by using ". aspx" as the suffix, you have been exposed to others and you are using the ASP. NET Framework. Such a potential hacker will have a clue on how to attack your website. URL rewriting can change the extension to ". X" or ". mysite", so that attackers can guess what framework your website uses.

Another security concern is that displaying your site directory and URL parameters in the URL usually allows hackers to obtain important information for front-end attacks. With this information, they can modify parameters or directly access related directories to secretly find a possible security vulnerability on your website. URL rewriting helps you hide this information without being discovered by hackers.

However, it is worth noting that URL rewriting is only a small part of the overall website security protection measures. Simply hiding a security vulnerability does not mean that the vulnerability does not exist. Therefore, make sure to test the security of your website in detail and fix the vulnerability.

4. Improve website availability and professionalism

Lengthy and non-user-friendly URLs usually bring availability issues to your website. Users will not always access your website from a link. Many times, you need to enter your website URL directly in your browser. If it is too long or does not agree with your memory, generally, users are not allowed to access your website. In addition, when users discuss websites, they will also have a certain impact on user communication.

In either case, keeping a website simple and concise is always a good idea. URL rewriting can help achieve this operation transparently without changing the underlying directory structure and Page name.

A website with good looks and good notes usually increases the professionalism and overall appearance of the website. This gives you the opportunity to show what you know or are doing.

Conclusion

The methods and ideas described in this article are only part of the overall solution for building a perfect website, however, I hope this article will give you a comprehensive understanding of how to implement and why URL rewriting can be used to improve your website.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.