Apache rewrite例子集合
在 httpd 中將一個網域名稱轉寄到另一個網域名稱
虛擬機器主機世界近期更換了網域名稱,新網域名稱為 www.wbhw.com, 更加簡短好記。這時需要將原來的網域名稱 webhosting-world.com, 以及論壇所在地址 webhosting-world.com/forums/ 定向到新的網域名稱,以便使用者可以找到,並且使原來的論壇 URL 繼續有效而不出現 404 未找到,比如原來的 http://www. webhosting-world.com/forums/-f60.html, 讓它在新的網域名稱下繼續有效,點擊後轉寄到 http://bbs.wbhw.com/-f60.html, 這就需要用 apache 的 Mod_rewrite 功能來實現。
在< virtualhost> 中添加下面的重新導向規則:
RewriteEngine On
# Redirect webhosting-world.com/forums to bbs.wbhw.com
RewriteCond %{REQUEST_URI} ^/forums/
RewriteRule /forums/(.*) http://bbs.wbhw.com/$1 [R=permanent,L]
# Redirect webhosting-world.com to wbhw.com
RewriteCond %{REQUEST_URI} !^/forums/
RewriteRule /(.*) http://www.wbhw.com/$1 [R=permanent,L]
添加了上面的規則以後, 裡的全部內容如下:
< virtualhost *:80>
ServerAlias webhosting-world.com
ServerAdmin admin@webhosting-world.com
DocumentRoot /path/to/webhosting-world/root
ServerName www.webhosting-world.com
RewriteEngine On
# Redirect webhosting-world.com/forums to bbs.wbhw.com
RewriteCond %{REQUEST_URI} ^/forums/
RewriteRule /forums/(.*) http://bbs.wbhw.com/$1 [R=permanent,L]
# Redirect webhosting-world.com to wbhw.com
RewriteCond %{REQUEST_URI} !^/forums/
RewriteRule /(.*) http://www.wbhw.com/$1 [R=permanent,L]
< /virtualhost>
URL重新導向例子一:
1.http://www.zzz.com/xxx.php-> http://www.zzz.com/xxx/
2.http://yyy.zzz.com-> http://www.zzz.com/user.php?username=yyy 的功能
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.zzz.com
RewriteCond %{REQUEST_URI} !^user/.php$
RewriteCond %{REQUEST_URI} /.php$
RewriteRule (.*)/.php$ http://www.zzz.com/$1/ [R]
RewriteCond %{HTTP_HOST} !^www.zzz.com
RewriteRule ^(.+) %{HTTP_HOST} [C]
RewriteRule ^([^/.]+)/.zzz/.com http://www.zzz.com/user.php?username=$1
例子二:
/type.php?typeid=* --> /type*.html
/type.php?typeid=*&page=* --> /type*page*.html
RewriteRule ^/type([0-9]+).html$ /type.php?typeid=$1 [PT]
RewriteRule ^/type([0-9]+)page([0-9]+).html$ /type.php?typeid=$1&page=$2 [PT]