[建站日誌] 虛擬主機主網域指向資料夾位置

這次移轉網站,我希望在虛擬主機上的資料夾整理能比較有組織性。假如我有兩個網域:primary and seconday domain (虛擬主機商一般允許可附加多個不同網域),然後主網域的前綴設爲 image (這也就是子網域 (sub-domain) 的設定議題),所有主網域的圖檔均可透過該子網域統一讀取。所以主要網域的規劃如下:

www.primarydomain.com (設爲主網域)
image.primarydomain.com (圖檔的讀取進入點)
www.secondarydomain.com(附加網域)

我希望資料夾的儲存位置設定爲:

\public_html\primarydomain => www.primarydomain.com
\public_html\primary_image => image.primarydomain.com
\public_html\secondarydomain => www.secondarydomain.com

但一般虛擬主機上的資料夾結構卻不是這樣設定。預設主網域規定一定要放在位於 \public_html 這個資料夾的根目錄上,但卻無法自行指定儲放於該目錄內的子資料夾內 (subfolder),而至於其它的子網域/附加網域,則是可以任意指定儲放的資料夾位置。

對於多個網站/網域的資料夾結構規劃而言,這並不合適。透過服務單詢問技術客服,得到的回答卻是只能這樣作。我對這結果當然不滿意,自行透過谷歌查找相關解決方案,發現到有同樣需求的用戶其實不少。因爲可能是 cPanel 的設計問題,預設確實無法這麼做,只能透過 .htaccess 的 Redirect 設定方式,但這種方式對一般用戶稍嫌不容易,所以主機商往往不會建議也不會主動提供這種做法。

先從谷歌搜尋關鍵字 "public_html primary domain subfolder",可以查找到一堆相關的資訊。然後我找到下列幾條提供解決方案的文章:
o Host Primary Domain from a subfolder.
o Redirecting the primary/main web host domain to a subfolder.
o 如何將「主域名」指向「子資料夾」

其實解決方法意外簡單,就是只要新增一個「.htaccess」檔案置於 \public_html 根目錄下,然後設定主網域名稱與對應的子資料夾位置。主要內容範本參考如下:

# .htaccess main domain to subfolder redirect
# Copy and paste the following code into the .htaccess file
# in the public_html folder of your hosting account
# make the changes to the file according to the instructions.
 
# Do not change this line.
RewriteEngine on
 
# Change yourdomain.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?yourmaindomain.com$
 
# Change 'subfolder' to be the folder you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/subfolder/
 
# Don't change this line.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
 
# Change 'subfolder' to be the folder you will use for your main domain.
RewriteRule ^(.*)$ /subfolder/$1
 
# Change yourdomain.com to be your main domain again.
# Change 'subfolder' to be the folder you will use for your main domain
# followed by / then the main file for your site, index.php, index.html, etc.
 
RewriteCond %{HTTP_HOST} ^(www.)?yourmaindomain.com$
RewriteRule ^(/)?$ subfolder/index.php [L]

至於子網域、附加網域的資料夾對應設定,基本都差不多,在 cPanel 界面上操作設定即可。

目前我這樣設定運作是相當正常,對於多網站/多網域的資料夾組織結構後也很乾淨容易管理,不錯!

文章導覽

   

共有 2 則迴響

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *