PHP實踐之路(二)apache虛擬主機配置

cyxlzzs發表於2013-06-09

PHP實踐之路(目錄索引)


一、環境

1)作業系統:windows xp
2)apache2.2

二、背景

當我們在開發專案或者在學習時,總會建立多個專案。這樣在apache中預設的工作目錄只有在htdocs目錄下。所以我們必須建立虛擬主機,讓我們的單臺計算機可以當多個伺服器來使用。這裡我們就需要配置虛擬主機

三、解決方案

1)如果只為了達到多個工作目錄的要求,可以在httpd.conf中配置<IfModule alias_module>模組,具體方式可以在網上找,但這個方式有缺陷,當工作目錄不在磁碟根目錄下時,解析路徑將會遇到問題
2)apache本身提供了虛擬主機配置的擴充套件,在\conf\extra在可以看到有一個檔案httpd-vhosts.conf,這個檔案就是配置虛擬主機用的。而虛擬主機配置基本上有兩種方式,一種是基於IP地址的,這種方式需要主機有多個獨立的IP;另一種的基於名字配置,這種方式更加的靈活,一個IP地址就可以通過名字來配置多個虛擬主機。下面我們主要講一下基於名字配置的多個虛擬主機的配置

四、實施步驟

1)釋放虛擬主機配置的擴充套件,在httpd.conf檔案中找到如下兩行
# Virtual hosts
#Include conf/extra/httpd-vhosts.conf
我們僅需要去掉Include前面的“#”即可達到目的,變成如下
# Virtual hosts
Include conf/extra/httpd-vhosts.conf

2)配置httpd-vhost.conf。配置如下
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# Use name-based virtual hosting.
#
NameVirtualHost *:80

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#


<VirtualHost *:80>
    ServerName www.cyxlgzs.com
	DirectoryIndex index.php 
    DocumentRoot "F:/MyWorkSpace/project/php/cyxlgzs"
	<Directory "F:/MyWorkSpace/project/php/cyxlgzs"> 
        Options Indexes FollowSymLinks 
        AllowOverride None 
        Order allow,deny 
        Allow from all 
	</Directory> 
</VirtualHost>

<VirtualHost *:80>
    ServerName www.first_php.com
	DirectoryIndex index.php 
    DocumentRoot "F:/MyWorkSpace/project/php/first_php"
	<Directory "F:/MyWorkSpace/project/php/first_php"> 
        Options Indexes FollowSymLinks 
        AllowOverride None 
        Order allow,deny 
        Allow from all 
	</Directory> 
</VirtualHost>

首先看到這一行
NameVirtualHost *:80

這裡指定了訪問的域名為*,也就是任意,然後埠是80.這裡的埠和httpd.conf中的埠配置一致,也就是httpd.conf中的如下一行
Listen 80

然後接下來我們配置了兩個VirtualHost,拿第一作為例子講一下
ServerName相當於是一個域名,也就是我們在瀏覽器中訪問的地址,這裡我們配置的是www.cyxlgzs.com
DirectoryIndex是主頁的配置,當訪問時不指定具體頁面時訪問的預設網頁,這裡我們是index.php
DocumentRoot專案的磁碟路徑
Directory配置的是一些訪問的許可權

3)配置域名和IP地址的對應關係。
因為我們的環境是在windows下,在本機測試時,如果不配置該項將導致衝突。我們找到C:/WINDOWS/system32/drivers/etc目錄下的hosts檔案(linux一般在/etc/hosts),用記事本開啟,新增如下兩項
127.0.0.1                     www.cyxlgzs.com
127.0.0.1                     www.first_php.com 

IP地址後面的域名和httpd-vhosts.conf檔案中新增的虛擬主機相對應

4)配置完成,重慶apache服務。在瀏覽器中輸入www.cyxlgzs.com和www.first_php.com進行測試

版權宣告:本文為博主原創文章,未經博主允許不得轉載。

相關文章