网站加速最佳实践 – 避免重定向

来源:互联网 发布:西方管理思想史 知乎 编辑:程序博客网 时间:2024/05/16 15:16

参考:http://developer.yahoo.com/performance/rules.html#redirects

 

Redirects are accomplished using the 301 and 302 statuscodes. Here's an example of the HTTP headers in a 301 response:

      
HTTP/1.1 301 Moved Permanently

      
Location: http://example.com/newuri

      
Content-Type: text/html

The browser automatically takes the user to the URLspecified in the Location field. All the information necessary fora redirect is in the headers. The body of the response is typically empty.Despite their names, neither a 301 nor a 302 response is cached in practiceunless additional headers, such as Expires or Cache-Control,indicate it should be. Themeta refresh tag and JavaScript are other ways to direct users to a differentURL, but if you must do a redirect, the preferred technique is to use thestandard 3xx HTTP status codes, primarily to ensure the back button workscorrectly.

 

The main thing to remember is that redirects slow down theuser experience. Inserting a redirect between the user and the HTML documentdelays everything in the page since nothing in the page can be rendered and nocomponents can start being downloaded until the HTML document has arrived.

 

 

如果少了网址最后的“/”会让重定向更慢!


One of the most wasteful redirects happens frequently andweb developers are generally not aware of it. It occurs when a trailing slash(/) is missing from a URL that should otherwise have one. For example, going tohttp://astrology.yahoo.com/astrologyresults in a 301 response containing a redirect to http://astrology.yahoo.com/astrology/(notice the added trailing slash). This is fixed in Apache by using Alias or mod_rewrite,or the DirectorySlash directive if you're using Apache handlers.

 

 

从旧网站链接到新网站通常会使用重定向,这样做虽然简单,但是会降低用户体验(速度)。

 

Connecting an old web site to a new one is another commonuse for redirects. Others include connecting different parts of a website anddirecting the user based on certain conditions (type of browser, type of useraccount, etc.). Using a redirect to connect two web sites is simple andrequires little additional coding. Although using redirects in these situationsreduces the complexity for developers, it degrades the user experience.Alternatives for this use of redirects include using Alias and mod_rewriteif the two code paths are hosted on the same server. If a domain name change is the cause of usingredirects, an alternative is to create a CNAME (a DNS record that creates analias pointing from one domain name to another) in combination with Aliasor mod_rewrite.

 

 

301 redirect: 301 代表永久性转移(Permanently Moved)

302 redirect: 302 代表暂时性转移(Temporarily Moved )

参考:http://blog.joycode.com/ghj/archive/2007/09/21/108696.aspx