开发者

Redirect ugly URLs to their cleaner version and/or rewrite them at the same time

I have been searching for ways to ch开发者_如何学Goange http://www.mysite.com/about.html to http://www.mysite.com/about but had no luck so far.

Is this possible?


RewriteEngine On
RewriteCond %{THE_REQUEST} \.html
RewriteRule ^(.+)\.html$ /$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.+)$ $1.html

Lines 2-3 take care of the case when the original request contains .html. This request is translated to a 301 redirect via [R=301] flag and further processing is terminated via the [L] flag.

Line 4 acts as a condition for line 5. Line 5 does the normal URL rewriting. I just appends .html to any URL does not end with .html.

Understanding the recursion:

Without the RewriteCond and [L] flags, the rules will create an infinite loop.

  1. A request such as about.html becomes about on line 3 and becomes about.html on line 5. [R] prevents that.
  2. A request such as about will become about.html on line 5, then mod_rewrite processes this URL again so that line 3 will change it back to about; but the RewriteCond will prevent that because it checks the original request sent by the browser, not the re-written one.


try to add this in your .htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜