dong1289 发表于 2015-8-5 09:10:57

如何配置apache虚拟主机

  实验目标:在apache实现基于域名的虚拟主机

  实验用的XAMPP版本为1.7.7,内含apache版本为2.2.21

  
  实验前准备:
  1. 为了测试不同的域名,在Windows/System32/drivers/etc/下觅得hosts文件,在其中添加实验用的域名若干,如 -

  127.0.0.1   test1.net

  127.0.0.1   test2.net

  如此,则在浏览器中输入该俩域名时,Windows将其解析为127.0.0.1本地地址。即,在浏览器中访问localhost, test1.net, test2.net均可访问XAMPP的欢迎页。
  
  2. 在apache目录下建立目录,以放置您不同的网站。为保护XAMPP原有的htdocs中的欢迎页内容,实验另外建立了与htdocs平级的htdocs1目录,在其下建立了test1.net, test2.net两个子目录用以放置实验用的网站。如下 -
  apache/htdocs1/test1.net - 放置test1.net网站内容
  apache/htdocs1/test2.net - 放置test2.net网站内容
  在这两个目录中各新建hello world一网页 index.html,内容 -







hello~, 这是[对应的网站名,用以区别].net
  
  实验步骤:
  1. 找到apache/conf/httpd.conf, 将其中的
  ServerAdmin
  ServerName
  DocumentRoot
  注释掉。
  
  2. 在httpd.conf中,找到行

  
Include "conf/extra/httpd-vhosts.conf"  如被注释则解注。该文件记载了虚拟主机的参数。[以前虚拟主机参数是直接填写在httpd.conf中的,为了更好地组织文件,将其分离出去,类似于某些编程语言一样。因此httpd.conf中include它,即相当于把它的内容填在了httpd.conf中。]

  
3. 这个httpd-vhosts.conf文件格式基本如下 -


#blah-blah
NameVirtualHost *:80
#blah-blah
#blah-blah

    ServerAdmin XXXXXXXX
    DocumentRoot "XXXXXXXX"
    ServerName XXXXXXX
    ServerAlias XXXXXX
    ErrorLog "logs/XXXXXX-error.log"
    CustomLog "logs/XXXXXXX-error.log" combined   
  需要修改的,就是中的参数了。这个可以参见apache官方文档。根据实验域名,可以增加两个:
  



    ServerAdmin adm@test1.net
    DocumentRoot "C:/xampp/htdocs1/test1.net"
    ServerName test1.net
    ServerAlias www.test1.net
    ErrorLog "logs/test1-error.log"
    CustomLog "logs/test1-access.log" combined
   
   
    order allow,deny
    allow from all
      


    ServerAdmin adm@test2.net
    DocumentRoot "C:/xampp/htdocs1/test2.net"
    ServerName test2.net
    ServerAlias www.test2.net
    ErrorLog "logs/test1-error.log"
    CustomLog "logs/test1-access.log" combined
   
   
    order allow,deny
    allow from all
      
  注意,如果不在各VirtualHost中定义Directory的可访问性,你将遇到的是Access Forbidden!就连原来的localhost也是。
  
  4. 由于之前注释掉了httpd.conf中的ServerName, DocumentRoot等,为了仍然能以localhost访问原XAMPP欢迎页,就在增加一个VirtualHost,如下 -



    ServerAdmin adm@localhost
    DocumentRoot "C:/xampp/htdocs"
    ServerName localhost
   
    ErrorLog "logs/localhost-error.log"
    CustomLog "logs/localhost-access.log" combined
   
   
    order allow,deny
    allow from all
      
  为了避免出错,把它放置在第一个Virtualhost位置。

  
  至此,apache基于域名的虚拟主机配置完成。可以通过http://localhost访问XAMPP欢迎页,通过http://test1.net和http://test2.net访问各自的主页。

  
  

  
  
页: [1]
查看完整版本: 如何配置apache虚拟主机