动态虚拟主机与 mod_rewrite

本文描述了如何使用mod_rewrite创建动态配置的虚拟主机。

任意主机名的虚拟主机

我们希望为在域名解析的每个主机名自动创建虚拟主机,而无需创建新的VirtualHost部分。

在本文中,假设我们将为每个用户使用主机名www.SITE.example.com,并从/ home/SITE/www中提供其内容。

解决办法:

RewriteEngine on

RewriteMap    lowercase int:tolower

RewriteCond   "${lowercase:%{HTTP_HOST}}"   "^www\.([^.]+)\.example\.com$"
RewriteRule   "^(.*)" "/home/%1/www$1"

内部tolower RewriteMap指令用于确保所使用的主机名都是小写的,因此必须创建的目录结构中没有歧义。

RewriteCond中使用的括号被捕获到后向引用%1%2等,而RewriteRule中使用的括号被捕获到后向引用$1$2等。

与本文档中讨论的许多技术一样,mod_rewrite实际上并不是完成此任务的最佳方法。相反,应该考虑使用mod_vhost_alias,因为除了提供静态文件(例如任何动态内容和Alias解析)之外,它还可以更加优雅地处理。

动态虚拟主机使用mod_rewrite

httpd.conf中的这个摘录与第一个示例完全相同。上半部分与上面的相应部分非常相似,除了一些更改,向后兼容性和使mod_rewrite部分正常工作所需的更改; 下半部分配置mod_rewrite来完成实际工作。

因为mod_rewrite在其他URI转换模块(例如,mod_alias)之前运行,所以必须告知mod_rewrite显式地忽略那些模块已经处理过的URL。并且,因为这些规则会绕过任何ScriptAlias指令,我们必须让mod_rewrite显式地实现这些映射。

# get the server name from the Host: header
UseCanonicalName Off

# splittable logs
LogFormat "%{Host}i %h %l %u %t \"%r\" %s %b" vcommon
CustomLog "logs/access_log" vcommon

<Directory "/www/hosts">
    # ExecCGI is needed here because we can't force
    # CGI execution in the way that ScriptAlias does
    Options FollowSymLinks ExecCGI
</Directory>

RewriteEngine On

# a ServerName derived from a Host: header may be any case at all
RewriteMap  lowercase  int:tolower

## deal with normal documents first:
# allow Alias "/icons/" to work - repeat for other aliases
RewriteCond  "%{REQUEST_URI}"  "!^/icons/"
# allow CGIs to work
RewriteCond  "%{REQUEST_URI}"  "!^/cgi-bin/"
# do the magic
RewriteRule  "^/(.*)$"  "/www/hosts/${lowercase:%{SERVER_NAME}}/docs/$1"

## and now deal with CGIs - we have to force a handler
RewriteCond  "%{REQUEST_URI}"  "^/cgi-bin/"
RewriteRule  "^/(.*)$"  "/www/hosts/${lowercase:%{SERVER_NAME}}/cgi-bin/$1"  [H=cgi-script]

使用单独的虚拟主机配置文件

这种安排使用更高级的mod_rewrite功能来计算从单独的配置文件到虚拟主机到文档根的转换。这提供了更大的灵活性,但需要更复杂的配置。

vhost.map文件应如下所示:

customer-1.example.com /www/customers/1
customer-2.example.com /www/customers/2
# ...
customer-N.example.com /www/customers/N

httpd.conf配置文件中应包含以下内容:

RewriteEngine on

RewriteMap   lowercase  int:tolower

# define the map file
RewriteMap   vhost      "txt:/www/conf/vhost.map"

# deal with aliases as above
RewriteCond  "%{REQUEST_URI}"               "!^/icons/"
RewriteCond  "%{REQUEST_URI}"               "!^/cgi-bin/"
RewriteCond  "${lowercase:%{SERVER_NAME}}"  "^(.+)$"
# this does the file-based remap
RewriteCond  "${vhost:%1}"                  "^(/.*)$"
RewriteRule  "^/(.*)$"                      "%1/docs/$1"

RewriteCond  "%{REQUEST_URI}"               "^/cgi-bin/"
RewriteCond  "${lowercase:%{SERVER_NAME}}"  "^(.+)$"
RewriteCond  "${vhost:%1}"                  "^(/.*)$"
RewriteRule  "^/cgi-bin/(.*)$"                      "%1/cgi-bin/$1" [H=cgi-script]

上一篇: Apache URL重写 下一篇: Apache认证和授权