六 27
pache2主配置文件: /etc/apache2/apache2.conf。其最后兩行為:
# Include the virtual host configurations:
Include /etc/apache2/sites-enabled/
顯然/etc/apache2/sites-enabled下存放著有關虛擬站點(VirtualHost)的配置。經查看,初始情況下,該目錄下包含一個符號連接:000-default -> ../sites-available/default
這里又引出另外一個配置目錄:/etcc/apache2/sites-available。這個目錄下放置了所有可用站點的真正配置文件,對于Enabled的站點,Apache2在sites-enabled目錄建立一個到sites-available目錄下文件的符號鏈接。
/etc/apache2/sites-available下有兩個文件:default和default-ssl。000-default鏈接的文件為default,我們就以default為例,看看一個VirtualHost的配置是啥樣的:
ServerAdmin webmaster@localhost
DocumentRoot /var/www
Options FollowSymLinks
AllowOverride None
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
… …
DocumentRoot是這個站點的根目錄,這樣Apache2啟動時會掃描/etc/apache2/sites-enabled中可用的website配置并加載。當用戶訪問localhost:80時,Apache2就將default站點根目錄/var/www下的index.html作為請求的回應返回給瀏覽器,你就會欣賞到的就是/var/www/index.html這個文件中的內容了。
Apache2的默認站點我們不要去動它。我們新增站點配置來滿足我們的要求。到這里我猜測一下你可能有兩類需求:
一是如何配置根據訪問的域名區分配置不通的站點?
二是在相同域名地址的情況下,如何通過訪問不同的端口獲得不同的站點?
我們先來看看第一種需求。第一種需求講的是我要在一個Apache2服務器上配置兩個站點:site1.com和site2.com。好,我們可以按照下面步驟來做:
* 建立配置文件
在sites-available中建立兩個站點的配置文件site1_com和site2_com:
sudo cp default site1_com
sudo cp default site2_com
編輯這兩個配置文件,以site1_com為例:
ServerAdmin webmaster@localhost
ServerName site1.com
DocumentRoot /var/www/site1_com
Options FollowSymLinks
AllowOverride None
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
… …
注意上面配置中:ServerName、DocumentRoot和Directory是我們重點關注的配置點。site1的ServerName為site1.com,根目錄為/var/www/site1_com,Directory同DocumentRoot。site2_com也做同樣的改動。
* 在sites-enabled目錄下建立符號鏈接:
sudo ln -s /etc/apache2/sites-available/site1_com /etc/apache2/sites-enabled/site1_com
sudo ln -s /etc/apache2/sites-available/site2_com /etc/apache2/sites-enabled/site2_com
* 在/var/www下建立site1_com和site2_com兩個目錄,然后修改目錄所有者:
sudo chown -R www-data site1_com site2_com/
* 在site1_com和site2_com中各自創建一個index.html文件,用于測試使用。
以site1_com下index.html為例,其內容為:Welcome To Site1。
* 重啟Apache2(sudo /init.d/apache2 restart)使配置生效。
* 修改/etc/hosts文件,便于測試。
添加如下兩行:
127.0.0.1 site1.com
127.0.0.1 site2.com
* 打開瀏覽器,輸入http://site1.com,之后不出意外你就會看到”Welcome to Site1“字樣。
第二類需求是希望通過端口號來區分虛擬站點。這個也不難,一些配置方法與上面內容雷同,這里就不詳說了。
比如以site2為例:我通過80端口訪問site2,可看到"Welcome to Site2”,從8080端口訪問site2,則會看到"Welcome to Site2 through 8080"。我們如何配置呢?
* 首先我們得讓apache2監聽端口8080
修改/etc/apache2/ports.conf,增加兩行:
NameVirtualHost *:8080
Listen 8080
* 在/etc/apache2/sites-available/下增加site2_com_8080,并在sites-enabled下建立符號連接。
site2_com_8080的主要配置如下:
ServerAdmin webmaster@localhost
ServerName site2.com
DocumentRoot /var/www/site2_com_8080
Options FollowSymLinks
AllowOverride None
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
… …
在/var/www下建立site2_com_8080目錄,方法同上。
重啟Apache2,訪問http://site2.com:8080,我們將看到“Welcome to Site2 through 8080”。
新聞熱點
疑難解答