[SEO][架站] 使用 Apache 的 ReWrite 設定讓 URL 變短(short URL)、變成靜態樣式

使用 Apache web server 的ReWrite 設定,很方便地可將原本是『postshow.php?PoId=178』樣式的動態產生頁面,變成『postshow_178.html』形式的 ‘靜態頁面’。

使用 ReWrite 的好處一方面可以讓 URL 看起來比較短,不帶參數的 ‘靜態頁面’ 形式對使用者來說比較習慣;另一方面是,一般認為有利於 SEO,搜尋引擎比較好抓。

在這僅舉個簡單例子:『postshow.php?PoId=178』樣式改成『postshow_178.html』形式的 ‘靜態頁面’。


Part I. Apache 的 httpd.conf 設定方面 (例如在 /usr/local/apache2/conf/httpd.conf, 以 httpd-2.2.x 為例)

1. 先確定自己的 Apache web server 有設定成支援 ReWrite。
動態載入 ReWrite engine 的設定下會在 httpd.conf 中看到這一行『LoadModule rewrite_module modules/mod_rewrite.so』。

2. 在 DocumentRoot 所屬的 Directory 設定內設定 ReWrite 參數。
ReWrite 的語法是:
RewriteRule <比對規則, 一般會含有正規表示式> <要導往的 URL> [旗標]

如以下範例:

…..
LoadModule rewrite_module modules/mod_rewrite.so
…..
<Directory “/usr/local/apache2/htdocs”>
Order allow,deny
Allow from all
Options FollowSymLinks
# 將 ReWrite engine 模式打開,預設是 off 的
RewriteEngine On
RewriteRule ^postshow_([0-9]+)\.html$ /postshow.php?PoId=$1 [L,QSA]
…..
</Directory>

另外,你可能會需要將『AllowOverride None』設定改成『AllowOverride All』。
如果是跑 VirtualHost,相關設定亦可放到 『 ….. 』中。

3. 重跑 Apache web server。

Part II. 程式輸出的 web 頁面內容相對應於 ReWrite 設定改成適當的格式。

1. 將原本 URL 是例如『postshow.php?PoId=178』樣式的都改成『postshow_178.html』格式。


ps: ReWrite 設定也可以用於 .htaccess 設定中,對於無法更動系統 httpd.conf 者還是適用。

節錄 [1] 中的正規表示式語法如下:
Text:
. Any single character
[chars] Character class: Any character of the class “chars”
[^chars] Character class: Not a character of the class “chars”
text1|text2 Alternative: text1 or text2

Quantifiers:
? 0 or 1 occurrences of the preceding text
* 0 or N occurrences of the preceding text (N > 0)
+ 1 or N occurrences of the preceding text (N > 1)

Grouping:
(text) Grouping of text
(used either to set the borders of an alternative as above, or
to make backreferences, where the Nth group can
be referred to on the RHS of a RewriteRule as $N)

Anchors:
^ Start-of-line anchor
$ End-of-line anchor

Escaping:
\char escape the given char
(for instance, to specify the chars “.[]()etc.)

更多的正規表示式和 rewrite_module 的介紹請參考:

  • [1] 2.X –> http://httpd.apache.org/docs-2.0/mod/mod_rewrite.html
  • [2] 1.3.X –> http://httpd.apache.org/docs/mod/mod_rewrite.html
  • 這篇文章的關鍵字(Keyword): short url, short urls, short url redirection, rewrite url

    One thought on “[SEO][架站] 使用 Apache 的 ReWrite 設定讓 URL 變短(short URL)、變成靜態樣式”

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.