一些背景知识:我一直想要建立动态虚拟主机一段时间。基本上我只是希望能够将一个文件夹放入我的虚拟主机文件夹中,只需让它在没有任何其他配置的情况下工作。我发现在Chrome中.localhost
的任何子域都与localhost
的行为相同。这意味着我可以将.localhost
用作我所有项目的TLD,而且我不必为每个要添加的新虚拟主机编辑HOSTS
文件。
我阅读了https://httpd.apache.org/docs/current/vhosts/mass.html上的文档,并找出了如何根据主机头创建动态虚拟主机。
在浏览了该网页和互联网上的其他资源后,我在httpd-vhosts.conf
文件中提出了以下配置。这使用.localhost
之前的部分来确定文件夹名称。
<VirtualHost *:80>
ServerAdmin admin@localhost
# Get the server name from the Host header
UseCanonicalName Off
# Log
LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon
CustomLog logs/vhost_access.log vcommon
ErrorLog logs/vhost_error.log
# Match domain name against a folder
VirtualDocumentRoot "C:/vhosts/%-2+"
<Directory "C:/vhosts/*">
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
Allow from all
Require all granted
</Directory>
</VirtualHost>
因此,通过此设置,我可以在vhosts
文件夹中创建一个包含所有html文档的新文件夹。因此,例如,如果我创建一个名为project1
的文件夹,我可以通过转到http://project1.localhost
来访问该文件夹。
现在我的主要问题是我并不总是需要创建一个新的虚拟主机。我只想创建一个随机的php文件,然后转到http://localhost/index.php
访问它。但是,使用上述配置,仅使用http://localhost
会导致错误。可能是因为VirtualDocumentRoot
指令中的模式使用了localhost
的子域,并且在我使用http://localhost
时没有子域。
根据上面的配置,是否有任何方法可以为localhost
创建一个硬编码的虚拟主机,并为localhost
的子域提供动态虚拟主机?
或者,我如何创建一个允许我这样做的配置:
http://localhost -----------------> C:/vhosts/
http://project1.localhost --------> C:/vhosts/project1
http://project2.localhost --------> C:/vhosts/project2
http://blog.project2.localhost ---> C:/vhosts/project2/blog
答案 0 :(得分:1)
我有一个解决方案,但它只是解决了部分问题。
<VirtualHost *:80>
ServerAdmin admin@localhost
ServerName localhost
DocumentRoot "C:/vhosts/"
</VirtualHost>
<VirtualHost *:80>
ServerAdmin admin@localhost
ServerName longnameyoullneveruse.blabla.localhost
ServerAlias *.localhost
DocumentRoot "C:/vhosts/"
RewriteEngine On
RewriteMap lowercase int:tolower
RewriteCond %{HTTP_HOST} ^(.*)\.localhost$
RewriteRule ^(.*)$ "C:/vhosts/${lowercase:%1}/$1"
# you should use all lowercase for subfolders' name
</VirtualHost>
这应符合您要求的前三行:
http://localhost -----------------> C:/vhosts/
http://project1.localhost --------> C:/vhosts/project1
http://project2.localhost --------> C:/vhosts/project2