apache - 如何为除 localhost 之外的所有域提供动态虚拟主机

标签 apache .htaccess configuration xampp virtualhost

一些背景知识:我一直想设置动态虚拟主机一段时间了。基本上,我只是希望能够将一个文件夹放入我的虚拟主机文件夹中,然后让它在没有任何其他配置的情况下工作。我发现在 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/

相关文章:

php - MySQL PHP 查询优化 - 反馈

.htaccess - .htaccess 是否可以返回 304 Not Modified

Android 表面在缓冲区之间闪烁

git - 如何防止 git commit 工具在提交后关闭?

php - 如何在 Windows 7 中将 PHP 5.3.28 升级到 PHP 5.5x

apache - .htaccess 中的通用 IP 规范化解决方案

.htaccess - 将特定的URL重写到其他目录

java - 如何将 Fop 配置文件加载到 FopFactory

javascript - SimpleHTTPServer 代码 404,消息未找到文件

apache - 如何使用 .htaccess 规则将 .php 重写为 .html?