2011-09-04

Apache用mod_rewrite配置子域名

Views: 16551 | 2 Comments

虽然用vhost可以支持子域名, 但不方便.

RewriteCond $1 !^bbs/
RewriteCond %{HTTP_HOST} bbs.example.com
RewriteRule (.*) /bbs/$1 [L]

RewriteCond $1 !^bbs/ 避免内部无限redirect.

或者支持无限子域名:

RewriteCond %{ENV:Rewrite-Done} !^Yes$
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com
RewriteRule (.*) /%1/$1 [E=Rewrite-Done:Yes,L]

注: Apache mod_rewrite 有一个严重的BUG, 无法获取自己设置的环境变量. 所以上面的代码有问题! 所以还是半自动:

RewriteCond $1 !^bbs/
RewriteCond $1 !^OTHER_SUBDOMAIN/
......
# BUG: RewriteCond %{ENV:Rewrite-Done} !^Yes$
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com
RewriteRule (.*) /%1/$1 [E=Rewrite-Done:Yes,L]

补充: xiaobin 提到可以使用 vhost_alias 模块. 我在他的基础之上做了改进, 结合 mod_rewrite, 可以更好的兼容www子域:

<VirtualHost *:80>
	ServerAlias ideawu.net *.ideawu.net
	VirtualDocumentRoot /home/work/htdocs/ideawu.net/%1

	RewriteEngine On
	RewriteCond %{HTTP_HOST} ^ideawu.net$
	RewriteRule /(.*) http://www.ideawu.net/$1 [R=301,L]
</VirtualHost>

Related posts:

  1. SSDB 数据库的图形化界面管理工具 – phpssdbadmin
  2. 链接包含”%2F”导致mod_rewrite失效
  3. Linux下编译安装Apache/Nginx/Lighttpd+PHP+MySQL
  4. lighttpd配置HTTPS(SSL)
  5. Tomcat网站server.xml设置
Posted by ideawu at 2011-09-04 22:26:02 Tags:

2 Responses to "Apache用mod_rewrite配置子域名"

Leave a Comment