概念:

Apache Rewirte 主要的功能就是實現URL的跳轉,它的正則運算式是基於Perl 語言。可基於伺服器級的(HTTPd.conf)和目錄級的 (.htaccess)兩種方式。如果要想用到rewrite模組,必須先安裝或載入rewrite模組。

Apache mod_rewrite 規則重寫的標誌一覽

1) R[=code](force redirect) 強制外部重定向:強制在替代字串加上HTTP://thishost[:thisport]/首碼重定向到外部的URL.如果code不指定,將用缺省的302 HTTP狀態碼。

2) F(force URL to be forbidden)禁用URL,返回403HTTP狀態碼。

3) G(force URL to be gone) 強制URL為GONE,返回410HTTP狀態碼。

4) P(force proxy) 強制使用代理轉發。

5) L(last rule) 表明當前規則是最後一條規則,停止分析以後規則的重寫。

6) N(next round) 重新從第一條規則開始運行重寫過程。

7) C(chained with next rule) 與下一條規則關聯:如果規則匹配則正常處理,該標誌無效,如果不匹配,那麼下面所有關聯的規則都跳過。

8) T=MIME-type(force MIME type) 強制MIME類型

9) NS (used only if no internal sub-request) 只用于不是內部子請求

10) NC(no case) 不區分大小寫

11) QSA(query string append) 追加請求字串

12) NE(no URI escaping of output) 不在輸出轉義特殊字元

實作:

首先要讓 Apache 支援 mod_rewrite,可以在 httpd.conf 看有沒有這一行

LoadModule rewrite_module modules/mod_rewrite.so

接下來要準備設定 mod_rewrite,原則上有二種寫法,一種是直接寫在 httpd.conf 裡面,另一種是寫在 .htaccess 裡面,若要寫在 .htaccess 也要特別注意 Apache 是否有支援,以 xampp.v182 來作說明,原則上預設是開啟的,它的 httpd.conf 內容為:

LoadModule rewrite_module modules/mod_rewrite.so

<Directory />
    AllowOverride none
    Require all denied
</Directory>

DocumentRoot "D:/AppServ/xampp.v182/htdocs"
<Directory "D:/AppServ/xampp.v182/htdocs">
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Require all granted
</Directory>

 

虛擬主機的設定 httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin polin.wei@localhost.bootstrap
    DocumentRoot "D:/AppServ/xampp.v182/htdocs/bootstrap"
    ServerName localhost.bootstrap
    ErrorLog "logs/bootstrap-error.log"
    CustomLog "logs/bootstrap-access.log" common
</VirtualHost>

 

在目錄 D:/AppServ/xampp.v182/htdocs/bootstrap 的 .htaccess

Options -Indexes
RewriteEngine on //開啟Rewrite功能
RewriteBase /

RewriteRule  ^about/(.*)/(.*)$ page.php?type=$1&name=$2 [NC,L]

 

這樣子,就可以將原先程式 http://localhost.bootstrap/page.php?type=polin&name=wei 變成 http://localhost.bootstrap/about/polin/wei

 

 

 

arrow
arrow
    文章標籤
    apache rewrite
    全站熱搜

    MIS 發表在 痞客邦 留言(0) 人氣()