Apache偽靜態Rewrite詳解_Linux

來源:互聯網
上載者:User

一、Rewrite規則簡介:
Rewirte主要的功能就是實現URL的跳轉,它的Regex是基於Perl語言。可基於伺服器級的(httpd.conf)和目錄級的 (.htaccess)兩種方式。如果要想用到rewrite模組,必須先安裝或載入rewrite模組。方法有兩種一種是編譯apache的時候就直接 安裝rewrite模組,別一種是編譯apache時以DSO模式安裝apache,然後再利用源碼和apxs來安裝rewrite模組。
二、在Apache配置中啟用Rewrite
開啟設定檔httpd.conf:

複製代碼 代碼如下:

1.啟用rewrite
# LoadModule rewrite_module modules/mod_rewrite.so 去除前面的 #

2.啟用.htaccess
在虛擬機器設定項中
AllowOverride None    修改為: AllowOverride All


二、Rewrite基本寫法
伺服器有設定檔不可能由我們來改,所以大多情況下要在網站的根目錄下建一個.htaccess檔案。
複製代碼 代碼如下:

RewriteEngine on    //啟動rewrite引擎
RewriteRule ^/index([0-9]*).html$ /index.php?id=$1   //“([0-9]*)” 代表範圍 用(.*)代表所有,下同。
RewriteRule ^/index([0-9]*)/$ /index.php?id=$1 [R]   //虛擬目錄

三、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) 不在輸出轉義特殊字元
例如:RewriteRule /foo/(.*) /bar?arg=P1%3d$1 [R,NE] 將能正確的將/foo/zoo轉換成/bar?arg=P1=zoo
13) PT(pass through to next handler) 傳遞給下一個處理
例如:
複製代碼 代碼如下:
RewriteRule ^/abc(.*) /def$1 [PT] # 將會交給/def規則處理
Alias /def /ghi

14) S=num(skip next rule(s)) 跳過num條規則
15) E=VAR:VAL(set environment variable) 設定環境變數

四、Apache rewrite例子
例子一:
同時達到下面兩個要求:
1.用http://www.jb51.net/xxx.php 來訪問 http://www.jb51.net/xxx/
2.用http://yyy.jb51.net 來訪問 http://www.jb51.net/user.php?username=yyy 的功能

複製代碼 代碼如下:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.jb51.net
RewriteCond %{REQUEST_URI} !^user.php$
RewriteCond %{REQUEST_URI} .php$
RewriteRule (.*).php$ http://www.jb51.net/$1/ [R]
RewriteCond %{HTTP_HOST} !^www.jb51.net
RewriteRule ^(.+) %{HTTP_HOST} [C]
RewriteRule ^([^.]+).jb51.net http://www.jb51.net/user.php?username=$1

例子二:

複製代碼 代碼如下:

/type.php?typeid=* –> /type*.html
/type.php?typeid=*&page=* –> /type*page*.html

RewriteRule ^/type([0-9]+).html$ /type.php?typeid=$1 [PT]
RewriteRule ^/type([0-9]+)page([0-9]+).html$ /type.php?typeid=$1&page=$2 [PT]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.