呃,相當古老的話題了,不過網上的資料實在是太坑爹,無奈只能自己動手做個備忘了。。。
這里不提虛擬目錄和主機頭的區別了,不懂得童鞋去面壁思過吧
多個虛擬目錄
首先把Apache安裝到D:\Program Files\Apache2.2目錄下,端口號設置為8080,安裝完成后默認的網站根目錄為D:\Program Files\Apache2.2\htdocs,通常我們可以在htdocs下面建立個文件夾MySite,然后在瀏覽器輸入:http://localhost:8080/MySite 這樣就可以看到我們自己的站點了。然而有時我們想把站點放到其它目錄下面,這時就需要配置虛擬目錄了
比如我們在D盤建立如下文件夾D:\Code\WebSite,然后通過http://localhost:8080/DemoSite來訪問這個站點
打開httpd.conf文件,搜索<IfModule alias_module> 節點,然后在節點內輸入以下內容:
#下面是虛擬目錄聲明格式 #Alias用來定義虛擬目錄及虛擬目錄路徑,其中虛擬目錄名稱用於URL訪問的路徑別名,可以和虛擬目錄名稱不同 #<Directory/>節點用於定義目錄的訪問權限等 # #Alias 虛擬目錄名稱 虛擬目錄路徑 #<Directory 虛擬目錄路徑> # Options Indexes FollowSymLinks # AllowOverride All # Order allow,deny # Allow from all #</Directory> #下面是具體的示例,/DemoSite是目錄別名 "D:/Code/WebSite"是虛擬目錄的實際路徑 Alias /DemoSite "D:/Code/WebSite" <Directory "D:/Code/WebSite"> Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all </Directory>
重啟Apache服務后,在瀏覽器輸入http://localhost:8080/DemoSite就可以正常訪問了
這里需要注意下目錄盡量使用"/",而不是使用"\",原因就是"\"代表轉義符有些情況下會導致莫名奇妙的錯誤,下面附上完整的<IfModule alias_module>節點以供參考

<IfModule alias_module> # # Redirect: Allows you to tell clients about documents that used to # exist in your server's namespace, but do not anymore. The client # will make a new request for the document at its new location. # Example: # Redirect permanent /foo http://localhost/bar # # Alias: Maps web paths into filesystem paths and is used to # access content that does not live under the DocumentRoot. # Example: # Alias /webpath /full/filesystem/path # # If you include a trailing / on /webpath then the server will # require it to be present in the URL. You will also likely # need to provide a <Directory> section to allow access to # the filesystem path. # # ScriptAlias: This controls which directories contain server scripts. # ScriptAliases are essentially the same as Aliases, except that # documents in the target directory are treated as applications and # run by the server when requested rather than as documents sent to the # client. The same rules about trailing "/" apply to ScriptAlias # directives as to Alias. # ScriptAlias /cgi-bin/ "D:/Program Files/Apache2.2/cgi-bin/" Alias /DemoSite "D:/Code/WebSite" <Directory "D:/Code/WebSite"> Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all </Directory> </IfModule>
多主機頭綁定
(就是在一個端口上綁定多個域名,然后每個域名可以指向不同的目錄進行訪問,主機頭是IIS里面的說法),打開httpd.conf文件,在文件最后添加如下內容
#多主機頭配置無需放在特定的節點下面,一般直接在配置文件底部添加即可 #NameVirtualHost addr[:port] 為一個基於域名的虛擬主機指定一個IP地址(和端口) #聲明主機頭必須加這條指令,否者主機頭配置不會生效 #VirtualHost節點下面ServerName就是要綁定的域名,DocumentRoot表示此域名指向的目錄 #本機測試的話請在hosts中進行域名綁定如 127.0.0.1 www.mysite1.com
NameVirtualHost *:8080 <VirtualHost *:8080> ServerName www.mysite1.com DocumentRoot "D:\Program Files\Apache2.2\htdocs" </VirtualHost> <VirtualHost *:8080> ServerName www.mysite2.com DocumentRoot "D:\Code\MySite" </VirtualHost>
配置好后,重啟apache服務,瀏覽器輸入www.mysite1.com:8080,就會自動定向到D:\Program Files\Apache2.2\htdocs站點了
輸入www.mysite2.com:8080就會自動定向到D:\Code\MySite站點,如此就可以實現在一個服務器上同時運行多個站點