apache url rewrite 的RewriteRule參數詳解


apache url rewrite 的RewriteRule參數詳解

我們經常會在apache那邊對一些url進行一些重寫操作,那么就會涉及到很多的重寫策略的選擇,比如重定向的方式,參數的處理,規則匹配的順序等。

比如我們某個應用會有下面的url rewrite規則:下面是對於域名imall.test.com訪問的時候需要重定向到http://page.test.com/channel/imall/index.html這個url上,

<VirtualHost *>
ServerName imall.test.com#if("${industry_port}"!="80"):${industry_port}#end

RewriteEngine on
RewriteCond %{HTTP_HOST} =imall.test.com [NC]
RewriteRule ^/$ http://page.test.com/channel/imall/index.html [L,R]
</VirtualHost>

之前是想上面這么寫的,但是發現瀏覽器的url變了,也就是R其實是外部重定向,那么我希望瀏覽器的url不改變,那么就需要內部重定向或者反向代理的設計。此時只能參考官方文檔了:http://httpd.apache.org/docs/2.2/rewrite/flags.html

這里列出很多的參數:在每條規則后面可以加上多個參數,每個參數用逗號分隔

RewriteRule pattern target [Flag1,Flag2,Flag3]

B (escape backreferences):非字母字符會被編碼,
比如有個url為search.php?term=x & y/z,那么此時不設置B參數時會被編碼成search.php?term=x%20&y%2Fz=,也是不對的,那么設置B參數之后會被編碼成/search.php?term=x%20%26%20y%2Fz,這樣對於url rewrite的規則才能被正確解析轉發。

C|chain 如果匹配,會繼續匹配下一條規則,如果不匹配則跳過后面所有規則;

CO|cookie 可以給當前url設置cookie,規則如:[CO=NAME:VALUE:DOMAIN:lifetime:path:secure:httponly]
示例:

RewriteEngine On
RewriteRule ^/index\.html - [CO=frontdoor:yes:.example.com:1440:/]

DPI|discardpathinfo 丟棄PATH_INFO 信息

E|env 設置環境變量 [E=VAR:VAL] [E=!VAR]
示例:

RewriteRule \.(png|gif|jpg) - [E=image:1]
CustomLog logs/access_log combined env=!image

F|forbidden 直接返回403狀態碼

RewriteRule \.exe - [F]

G|gone 返回410 狀態碼,表示資源不再可用

RewriteRule oldproduct - [G,NC]

H|handler 指定請求被某個handler處理,下面這個url表示被php處理引擎處理

RewriteRule !\. - [H=application/x-httpd-php]

L|last 匹配了就不再匹配后面的規則

RewriteBase /
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule ^(.*) /index.php?req=$1 [L,PT]

N|next 重新從第一條規則開始匹配

RewriteRule (.*)A(.*) $1B$2 [N]

NC|nocase 大小寫不敏感

RewriteRule (.*\.(jpg|gif|png))$ http://images.example.com$1 [P,NC]

NE|noescape 不轉碼特殊字符,默認是會把&,?等特殊字符轉成16進制編碼,

RewriteRule ^/anchor/(.+) /bigpage.html#$1 [NE,R]

NS|nosubreq 規則不作用於子請求上, SSI (Server Side Include)

P|proxy 做為反向代理轉發請求,這樣瀏覽器url就不會改變

RewriteRule /(.*)\.(jpg|gif|png) http://images.example.com/$1.$2 [P]

PT|passthrough url作為一個文件路徑處理

Alias /icons /usr/local/apache/icons
RewriteRule /pics/(.+)\.jpg /icons/$1.gif [PT]

QSA|qsappend 帶上query參數

RewriteRule /pages/(.+) /page.php?page=$1 [QSA]

R|redirect 重定向 默認302 重定向

S|skip 跳過不想執行的規則匹配

# Is the request for a non-existent file?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# If so, skip these two RewriteRules
RewriteRule .? - [S=2]
RewriteRule (.*\.gif) images.php?$1
RewriteRule (.*\.html) docs.php?$1

T|type 指定MIME type 類型

# Serve .pl files as plain text
RewriteRule \.pl$ - [T=text/plain]

# Files with 'IMG' in the name are jpg images.
RewriteRule IMG - [T=image/jpg]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM