如何配置apache虛擬主機
作者:佚名 時間:2012-05-22 分享到:
1、簡單的動態虛擬主機
# 從 host: 頭中取得服務器名字 server name
usecanonicalname off
# 這里的日志格式,可以在將來通過第一個參數域來分隔不同的虛擬主機的日志
logformat "%v %h %l %u %t /"%r/" %s %b" vcommon
customlog logs/access_log vcommon
# 在返回請求的文件名的路徑中包含進服務器名字: server name
virtualdocumentroot /www/hosts/%0/docs
virtualscriptalias /www/hosts/%0/cgi-bin
2、更為有效的基于 ip 地址的虛擬主機
# 從 ip 地址反解析得到服務器名字(server name)
usecanonicalname dns
# 在日志中包含 ip 地址,便于后續分發
logformat "%a %h %l %u %t /"%r/" %s %b" vcommon
customlog logs/access_log vcommon
# 在文件路徑中包含 ip 地址
virtualdocumentrootip /www/hosts/%0/docs
virtualscriptaliasip /www/hosts/%0/cgi-bin
二、使用 mod_rewrite
1、使用 mod_rewrite 實現簡單的動態虛擬主機
# 從 host: 頭獲取服務器名字
usecanonicalname off
# 可分割的日志
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
## 首先處理普通文檔:
# 允許變名 /icons/ 起作用 - 其他變名類同
rewritecond %{request_uri} !^/icons/
# 允許 cgisrewritecond %{request_uri} !^/cgi-bin/
# 開始“變戲法”
rewriterule ^/(.*)$ /www/hosts/${lowercase:%{server_name}}/docs/$1
## 現在處理 cgis - 我們需要強制使用一個 mime 類型
rewritecond %{request_uri} ^/cgi-bin/
rewriterule ^/(.*)$ /www/hosts/${lowercase:%{server_name}}/cgi-bin/$1 [t=application/x-httpd-cgi]
# 好了!
2、使用獨立的虛擬主機配置文件 vhost.map
vhost.map 文件包含了類似下面的內容:
www.customer-1.com /www/customers/1
www.customer-2.com /www/customers/2
# ...
www.customer-n.com /www/customers/n
http.conf 包含了:
rewriteengine on
rewritemap lowercase int:tolower
# 定義映像文件
rewritemap vhost txt:/www/conf/vhost.map
# 和上面的例子一樣,處理變名
rewritecond %{request_uri} !^/icons/
rewritecond %{request_uri} !^/cgi-bin/
rewritecond ${lowercase:%{server_name}} ^(.+)$
# 這里做基于文件的重新映射
rewritecond ${vhost:%1} ^(/.*)$
rewriterule ^/(.*)$ %1/docs/$1
rewritecond %{request_uri} ^/cgi-bin/
rewritecond ${lowercase:%{server_name}} ^(.+)$
rewritecond ${vhost:%1} ^(/.*)$
rewriterule ^/(.*)$ %1/cgi-bin/$1