Apache-2.2

如何在Apache2的VirtualDocumentRoot中配置和組合萬用字元域和子域?

  • November 17, 2014

httpd-vhosts.conf

<Directory "/Volumes/DATA/websites">
   Options Indexes MultiViews FollowSymLinks
   AllowOverride All
   Order allow,deny
   Allow from all
   Require all granted
</Directory>

<Virtualhost *:80>
   VirtualDocumentRoot "/Volumes/DATA/websites/default"
   ServerName default.dev
   UseCanonicalName Off
</Virtualhost>

<Virtualhost *:80>
   VirtualDocumentRoot "/Volumes/DATA/websites/%1/www"
   ServerAlias *.dev
   UseCanonicalName Off
</Virtualhost>

目前處理請求如下:

alpha.dev   -> /Volumes/DATA/websites/alpha/www
beta.dev    -> /Volumes/DATA/websites/beta/www

是否可以有萬用字元域子域?例如:

alpha.dev       -> /Volumes/DATA/websites/alpha/www
img.alpha.dev   -> /Volumes/DATA/websites/alpha/img
cdn.alpha.dev   -> /Volumes/DATA/websites/alpha/cdn

beta.dev        -> /Volumes/DATA/websites/beta/www
docs.beta.dev   -> /Volumes/DATA/websites/beta/docs
blog.beta.dev   -> /Volumes/DATA/websites/beta/blog

根據此文件,可以使用 FQDN 的多個部分。在您的配置中,您使用%1的對應子域。如果 FQDN 是img.alpha.dev則將%1導致img%2它導致的域相對應,並且alpha%0FQDN相對應。img.alpha.dev``%0

實現以下配置:

<VirtualHost *:80>
   ServerAlias *
   VirtualDocumentRoot /var/www/%2/%1
</VirtualHost>

/etc/httpd/conf/httpd.conf,執行mkdir -p /var/www/mydomain/info && echo helloworld > /var/www/mydomain/info/index.html,重新啟動httpd和導航到http://info.mydomain.com/結果helloworld

但是,如果更多地指定了 ServerAlias,例如:

<VirtualHost *:80>
   ServerAlias *.mydomain.com
   VirtualDocumentRoot /var/www/%1
</VirtualHost>  

執行mkdir -p /var/www/info && echo test2_param_one > /var/www/info/index.html並導航info.mydomain.comtest2_param_one.

<VirtualHost *:80>
   ServerAlias *.mydomain.com
   VirtualDocumentRoot /var/www/%0
</VirtualHost>

執行mkdir -p /var/www/info.mydomain.com && echo test2_param_all > /var/www/info.mydomain.com/index.html並導航info.mydomain.comtest2_param_all.

總之,以下程式碼段有效:

<VirtualHost *:80>
   ServerAlias *.*.dev
   VirtualDocumentRoot /var/www/%2/%1
</VirtualHost>
<VirtualHost *:80>
   ServerAlias *.dev
   VirtualDocumentRoot /var/www/%1/test
</VirtualHost>

mkdir -p /var/www/alpha/test && echo test5 > /var/www/alpha/test/index.html, mkdir -p /var/www/alpha/img && echo test10 > /var/www/alpha/img/index.html, 導航到http://alpha.dev/退貨test5和導航到http://img.alpha.dev/退貨test10

引用自:https://serverfault.com/questions/644648