一些背景知识:我一直想设置动态虚拟主机一段时间了。基本上,我只是希望能够将一个文件夹放入我的虚拟主机文件夹中,然后让它在没有任何其他配置的情况下工作。我发现在 chrome 中 .localhost
的任何子域的行为都与 localhost
相同。这意味着我可以使用 .localhost
作为我所有项目的 TLD,并且无需为我想要添加的每个新虚拟主机编辑 HOSTS
文件。
我阅读了 https://httpd.apache.org/docs/current/vhosts/mass.html 上的文档并弄清楚如何根据主机 header 拥有动态虚拟主机。
阅读该页面和互联网上的其他资源后,我在 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
时没有子域。
tl;博士:
根据上面的配置,有没有办法为 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
最佳答案
我有一个解决方案,但它只能解决您的部分问题。
<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
关于apache - 如何为除 localhost 之外的所有域提供动态虚拟主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40186388/