【筆記】Apache2 啟用 conf 檔案與 Virtual Host 轉址設定

最近將使用了四年的 domain name (guand.me) 換成 jsy.tw 了,算是因應去年將站名從 Guand 改成 JS Ying,而且網址更短也更好記了。

跟以往一樣,在更改 domain name 的過程中將一些會用到的步驟紀錄下來,給自己也給大家一個參考。

本篇文章適用於 Ubuntu 14 的 apache2 環境。

/etc/apache2/apache2.conf

apache2 的設定檔,基本上不用去更動預設值,但我覺得可以稍微看一下設定的描述,這邊就不再贅述。

/etc/apache2/sites-available
/etc/apache2/sites-enable

Sites 資料夾是放 Virtual Host 的設定檔,我們會把各種不同 Virtual Host 設定檔通通放在 sites-available 裡面,而使用 a2ensite 和 a2dissite 兩種指令去 enable 或 disable 它。被 enable 的設定檔就會出現捷徑在 sites-enable 資料夾裡,apache 重啟後,apache2.conf 就會吃到 sites-enabled 裡的捷徑指向的設定檔。

(指令)啟用 sites-available 裡的設定檔:

$ sudo a2ensite xxx.conf

啟用後,sites-enabled 資料夾呈現如下圖:

https://jhihsiyingweb.s3.amazonaws.com/Blog/2020.01.06+Apache2+%E5%95%9F%E7%94%A8+conf+%E6%AA%94%E8%88%87+Virtual+Host+%E8%BD%89%E5%9D%80/sites-enabled.png
a2ensite jsy.tw.conf 後的 sites-enabled 資料夾

(指令)關閉設定檔:

$ sudo a2dissite xxx.conf

(指令)apache 重啟:

$ sudo service apache2 restart

Virtual Host 設定(/etc/sites-available/xxx.conf)

轉址可以寫在 Virtual Host 設定檔裡,也可以寫在 .htaccess 裡,這裡以 Virtual Host 設定檔為例

記得先打開 Virtual Host 允許覆寫的設定!

Step1. 打開 apache 設定檔(/etc/apache2/apache2.conf )

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
<Directory>

Step2. 將 AllowOverride 改成 All。

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
<Directory>

接下來就可以編輯 Virtual Host 設定檔了。

以沒有 SSL 協定的 http://your.new.domain (80 port) 為例,當 user 以 http://your.new.domain 進來時,apache 會將根目錄 /var/www/html 呈現給 user。設定如下:

<IfModule mod_ssl.c>
 <VirtualHost your.new.domain:80>
   ServerName your-server-name
DocumentRoot /var/www/html
  </VirtualHost>
</IfModule>

Virtual Host 轉址設定

當 user 是以 http://your.old.domain 進來時,因為 RewriteEngine 是 On 啟動重寫功能,依照 RewriteRule 重寫規則 (.*)$ http://your.new.domain$1 [L,R=301] 將不論你是在 your.old.domain 的任何一層網址連進來,都可以將 your.old.domain 轉成 your.new.domain 並回覆 user 原本在的那一層。

<IfModule mod_ssl.c>
 <VirtualHost your.old.domain:80>
   ServerName your-server-name
RewriteEngine On
   RewriteRule (.*)$ http://your.new.domain$1 [L,R=301]
  </VirtualHost>
</IfModule>

上段設定的使用案例:以 http://your.old.domain/blog/2020-01-01 進來會被強制轉址到 http://your.new.domain/blog/2020-01-01。

(若 RewriteRule 僅寫了 http://your.new.domain,則不論 user 是在哪一層,只要是 http://your.old.domain/XXX/XXX/XXX 都會被轉成 http://your.new.domain)

R=301, R=302 差別

301 與 302 都是 http 狀態,代表 URL 發生轉移。而 301 代表 URL 的永久轉移,當採取了此設定,不只 URL 的轉移,連搜尋引擎對於原 URL 的 Page Rank 和流量也會一起轉移。也就是說 Google 搜尋引擎會漸漸新的 URL 取代道舊的 URL。

302 用在暫時性轉移,搜尋引擎會保留新舊 URL 的 PageRank 和流量,假設若今天有個期間限定活動需要暫時轉址到新 URL 即可使用 302。

任何更動 apache 的設定都要重新啟動 apache 才會生效。

$ sudo service apache2 restart
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments