顯示具有 RewriteRule 標籤的文章。 顯示所有文章
顯示具有 RewriteRule 標籤的文章。 顯示所有文章

2014年1月24日 星期五

[引用] URL Rewrite(網址重寫)語法教學

引用來源: http://readily-notes.blogspot.tw/2011/11/url-rewrite.html

URL Rewrite是一種REST (Representational State Transfer,表徵狀態轉移)的相關技術,它可以在 Web Server 中,針對使用者所提供的 URL 進行轉換後,再傳入 Web Server 中的程式處理器。

使用者可以使用較直覺的方式來輸入 URL(這也是 REST 的主要目的),是搜尋引擎最佳化(SEO)的作法之一。而應用程式開發者可以利用這個機制來將參數隱藏起來,可避免讓網路上的惡意使用者收集到有利於發動攻擊的資訊。

引用:URL重寫

在 IIS 上安裝的方式我就不多說了,大家可以 google 一下,google 搜尋 " IIS Rewrite 安裝",關鍵詞都下好了,服務到家了吧 ! ( 請依電腦狀況做調整 )

本來想自己寫一篇的,但我發現有同好寫的很完整,所以就轉載了,我也該好好看看、好好學習,寫得蠻詳細的,最底下還有一些參考的網址,也可以參考。

以下引用:.htaccess语法,伪静态中的RewriteCond和RewriteRule使用说明 (http://gezhe.org/109.html)

1、.htaccess 語法簡介

RewriteEngine ON
RewriteCond %{HTTP_HOST} ^abc.com$ [OR]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ http://www.888.com/ [R=301,L]

RewriteEngine on
RewriteCond %{ HTTP_HOST } ^888.com
RewriteRule ^(.*)$ http://888.com/hot$1 [R=301,L]
RewriteCond %{ HTTP_HOST } ^www.888.com
RewriteRule ^(.*)$ http://www.888.com/hot$1 [R=301,L]




1.1、 RewriteCond的語法如下:
RewriteCond TestString CondPattern [Flags]
TestString 是指一個文本格式的條件,例子中用的是環境變量名HTTP_HOST所包含的內容(Name= Value),這是一個map(鍵值對)格式的數據類型。

CondPattern 是條件參數,這兒以第一個例子為例,就是abc.com。

Flags 標識是是第三個參數,可以用來緊跟下一個條件,這兒用OR表示或者,如果沒有[Flags],則用隱含的AND,表示並且。

其它的還可以NC等等,表示忽略大小寫RewriteCond就像我們程序中的if語句一樣,表示如果符合某個或某幾個條件則執行RewriteCond 下面緊鄰的RewriteRule語句,這就是RewriteCond最原始、基礎的功能,為了方便理解,下面來看看幾個例子。

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} ^Mozilla/5.0.*
RewriteRule index.php index.m.php
RewriteCond %{HTTP_USER_AGENT} ^Lynx.*
RewriteRule index.php index.L.php
RewriteRule index.php index.b.php


上面語句的作用是當你是用FF瀏覽器訪問index.php這個文件的時候,會自動讓你訪問到index.m.php這個文件,當你是用一些移動終端訪問 的時候,會讓你對index.php這個文件的訪問實際訪問的是index.L.php去,如果你是用其它的瀏覽器訪問的時候,會讓你跳到 index.b.php。在說形像一點,上面的語句就等同於程序裡面的下面語句(依PHP語句為例):

if($_SERVER['HTTP_USER_AGENT'] == 'Mozilla/5.0′)
{
//跳轉到對index.m.php的訪問
}
else if($_SERVER['HTTP_USER_AGENT'] == 'Lynx')
{
//跳轉到對index.L.php的訪問
}
else
//跳轉到對index.b.php的訪問

再看例2:
RewriteCond %{HTTP_REFERER} (www.test.cn)
RewriteRule (.*)$ test.php


上面語句的作用是如果你訪問的上一個頁面的主機地址是www.test.cn,則無論你當前訪問的是哪個頁面,都會跳轉到對test.php的訪問。

再看例3:
RewriteCond %{REMOTE_HOST} ^host1.* [OR]
RewriteCond %{REMOTE_HOST} ^host2.* [OR]
RewriteCond %{REMOTE_HOST} ^host3.*
RewriteRule (.*)$ test.php


上面語句的作用是如果你的地址是host1或host2或host3的時候,則就跳到對test.php。

從這裡可以看出,RewriteCond語句之間默認的是AND,如果想要OR,則要明確的寫出來。



下面是自己收藏的一些有用的重寫規則:
RewriteCond %{REQUEST_FILENAME} !-f //如果文件存在,就直接訪問文件,不進行下面的RewriteRule.(不是文件或文件不存在就執行重寫)
RewriteCond %{REQUEST_FILENAME} !-d //#如果目錄存在就直接訪問目錄不進行RewriteRule
RewriteCond %{REQUEST_URI} !^.*(.css|.js|.gif|.png|.jpg|.jpeg)$ //#如果是這些後綴的文件,就直接訪問文件,不進行Rewrite

1.2、RewriteRule的語法如下:
RewriteRule Pattern Substitution [Flags]

其中的Pattern就是參數,一般為一些文件的擴展名,Substitution是用來替換前面用的,這兒的Flags,常用的R表示 redirect(強制重定向),F表示forbidden(禁止訪問),L表示last(最後),通常當你希望停止重寫操作而立即重定向時,可用它。

Flags 還有更多用法,以下引用 ISAPI Rewrite 2 规则中文使用说明

不管大小寫強行指定字符匹配,這個FLAG影響RewriteRule指令和相應的RewriteCond 指令

F (Forbidden)

對客戶端做反應,停止REWRITING進程並且發送403錯誤,注意在這種情況下FORMATSTRING 是無用的並可以設置為任何非空字符串。

L (last rule)

不應用任何重寫規則在此停止重寫進程,使用這個FLAG以阻止當前被重寫的URI被後面的規則再次重寫

N (Next iteration)

強制REWRITINGENGINE調整規則目標並且從頭重啟規則檢查(所有修改將保存),重啟次數由RepeatLimit指定的值限制,如果這個數值超過N FLAG將被忽略

NS (Next iteration of the same rule)

以N標記工作不從相同的規則重啟規則規則進程(例如強制重複規則應用),通過RepeatLimit指令指定一個反复實行某一規則的最大數目,

P (force proxy)

強制目的URI在內部強制為代理需求並且立即通過ISAPI擴展應付代理需求,必須確認代理字符串是一個有效的URI包括協議主機等等否則代理將返回錯誤

R (explicit redirect)

強制服務器對客戶端發出重定向指示即時應答,提供目的URI的新地址,重定向規則經常是最後規則

RP (permanent redirect)

幾乎和[R]標記相同但是發布301HTTP狀態而不是302HTTP狀態代碼

U (Unmangle Log)

當URI是源需求而不是重寫需求時記載URI

O (nOrmalize)

在實行之前標準化字符串。標準化包括URL-ENCODING,不合法的字符的再移動等,這個標記對於URLS和URLS-ENDODED頭是有用的

CL (Case Lower)

小寫

CU (Case Upper)

大寫1.3、.htaccess 用到的正則表達式

元字符^(和數字6在同一個鍵位上的符號)和$都匹配一個位置,這和\b有點類似。

  • ^ 匹配你要用來查找的字符串的開頭
  • $ 匹配結尾。
    比如一個網站如果要求你填寫的QQ號必須為5位到12位數字時,可以使用:^\d{5,12}$。
  • \b代表著單詞的開頭或結尾,也就是單詞的分界處,它只匹配一個位置。
  • \d是個新的元字符,匹配一位數字(0,或1,或2,或……)。
  • 例:0\d{2}-\d{8} 匹配這樣的字符串:以0開頭,然後是兩個數字,然後是一個連字號“-”,最後是8個數字(也就是中國的電話號碼。當然,這個例子只能匹配區號為3位的情形)。
  • \s匹配任意的空白符,包括空格,製表符(Tab),換行符,中文全角空格等。
  • \w匹配字母或數字或下劃線或漢字
  • \來取消字符的特殊意義。可使用\.和\*。要查找\本身,也得用\\.
  • [ ] 匹配沒有預定義元字符的字符集合,在方括號裡列出它們就行了
    例: [aeiou]就匹配任何一個英文元音字母,[.?!]匹配標點符號(.或?或!)
    [0-9]代表的含意與\d就是完全一致的:一位數字;同理[a-z0-9A-Z_]也完全等同於\w
  • .匹配除 “\n” 之外的任何單個字符。要匹配包括'\n' 在內的任何字符,請使用象'[.\n]' 的模式。
    例子:\(?0\d{2}[) -]?\d{8}。


像(010)88886666,或022-22334455,02912345678等。
分析:首先是一個轉義字符\(,它能出現0次或1次(?),
然後是一個0,後面跟著2個數字(\d{2}),
然後是)或-或空格中的一個,它出現1次或不出現(?),最後是8個數字(\d{8})。
  • * 重複零次或更多次
  • + 重複一次或更多次
  • ? 重複零次或一次
  • {n} 重複n次
  • {n,} 重複n次或更多次
  • {n,m} 重複n到m次

1.4 .htaccess放置參考wordpress的偽靜態寫法

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress


——————————————————————————————-

在Windows 資源管理器裡面不允許你建立.htaccess 這樣只有擴展名的文件。
用記事本編寫好內容後,保存時,文件名要輸入為“.htaccess”

或者先將文件保存為其他名字,例如app.htaccess。

然後進入命令行窗口(通過開始菜單運行cmd.exe 程序即可),

輸入ren app.htaccess .htaccess 命令來對文件改名。

——————————————————————————————-
常見的.htaccess應用舉例

防止盜鏈,如果來得要訪問jpe jpg bmp png結尾的url 用戶不是來自我們的網站,那麼讓他看一張我們網站的展示圖片。
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+.)?mysite.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*.(jpe?g|gif|bmp|png)$ / images/nohotlink.jpg [L]


網站升級的時候,只有特定IP才能訪問,其他的用戶將看到一個升級頁面
RewriteEngine on
RewriteCond %{REQUEST_URI} !/upgrade.html$
RewriteCond %{REMOTE_HOST} !^24\.121\.202\.30
RewriteRule $ http://www.linuxidc.com/upgrade.html [R=302,L]


把老的域名轉向新域名
# redirect from old domain to new domainRewriteEngine OnRewriteRule ^(.*)$http://www.yourdomain.com/$1[R=301,L]

RewriteEngine On
RewriteRule index.html index.php

比如:http://www.3code.cn/index.html -> http://www.3code.cn/index.php

RewriteRule ^test([0-9]*).html$ test.php?id=$1

比如:http://www.3code.cn/test8.html -> http://www.3code.cn/test.php?id=8

RewriteRule ^cat-([0-9]+)-([0-9]+)\.html$ cat.php?id1=$1&id2=$2

比如:http://www.3code.cn/cat-1-3.html -> http://www.3code.cn/cat.php?id1=1&id2=3

RewriteRule ^cat-([a-zA-Z0-9\-]*)-([0-9]+)-([0-9]+)\.html$ cat.php?id0=$1&id1=$2 &id2=$3

比如:http://www.3code.cn/cat-zbc2ac-3-5.html -> http://www.3code.cn/cat.php?id0=zbc2ac&id1=3&id2=5

RewriteRule ^cat1-([0-9]+)-([0-9]+)-([0-9]+)\.html$ cat1.php?id1=$1&id2=$2&id3=$3

比如:http://www.3code.cn/cat1-4-3-8.html -> http://www.3code.cn/cat1.php?id1=4&id2=3&id3=8

RewriteRule ^cat([0-9]*)/$ cat.php?id1=$1

比如:http://www.3code.cn/cat5/ -> http://www.3code.cn/cat.php?id1=5

RewriteRule ^catm([0-9]*)/([0-9]*)/$ catm.php?id1=$1&id2=$2

比如:http://www.3code.cn/catm6/3/ -> http://www.3code.cn/catm.php?id1=6&id2=3

更多例子:
1. 使用.htaccess 創建自定義的出錯頁面。對於Linux Apache來說這是一項極其簡單的事情。使用下面的.htaccess語法你可以輕鬆的完成這一功能。 (把.htaccess放在你的網站根目錄下)
ErrorDocument 401 /error/401.php
ErrorDocument 403 /error/403.php
ErrorDocument 404 /error/404.php
ErrorDocument 500 /error/500.php



2. 設置網站的時區
SetEnv TZ America/Houston

3. 阻止IP列表
有些時候,你需要以IP地址的方式阻止一些訪問。無論是對於一個IP地址還是一個網段,這都是一件非常簡單的事情,如下所示:

allow from all
deny from 145.186.14.122
deny from 124.15

Apache對於被拒絕的IP會返回403錯誤。

4. 把一些老的鏈接轉到新的鏈接上——搜索引擎優化SEO
Redirect 301 /d/file.htmlhttp://www.htaccesselite.com/r/file.html

5. 為服務器管理員設置電子郵件。
ServerSignature EMail
SetEnv SERVER_ADMINdefault@domain.com


6. 使用.htaccess 訪止盜鏈。如果你網站上的一個圖片被別的N多的網站引用了,那麼,這很有可能會導致你服務器的性能下降,使用下面的代碼可以保護某些熱門的鏈接不被過多的引用。

Options +FollowSymlinks
# Protect Hotlinking
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?domainname.com/[nc]
RewriteRule .*.(gif|jpg|png)$http://domainname.com/img/hotlink_f_o.png[nc]

7. 阻止 User Agent 的所有請求

## .htaccess Code :: BEGIN
## Block Bad Bots by user-Agent
SetEnvIfNoCase user-Agent ^FrontPage [NC,OR]
SetEnvIfNoCase user-Agent ^Java.* [NC,OR]
SetEnvIfNoCase user-Agent ^Microsoft.URL [NC,OR]
SetEnvIfNoCase user-Agent ^MSFrontPage [NC,OR]
SetEnvIfNoCase user-Agent ^Offline.Explorer [NC,OR]
SetEnvIfNoCase user-Agent ^[Ww]eb[Bb]andit [NC,OR]
SetEnvIfNoCase user-Agent ^Zeus [NC]

Order Allow,Deny
Allow from all
Deny from env=bad_bot


## .htaccess Code :: END
8. 把某些特殊的IP地址的請求重定向到別的站點
ErrorDocument 403http://www.youdomain.com
Order deny,allow
Deny from all
Allow from 124.34.48.165
Allow from 102.54.68.123


9. 直接找開文件而不是下載– 通常,我們打開網上文件的時候總是會出現一個對話框問我們是下載還是直接打開,使用下面的設置就不會出現這個問題了,直接打開。
AddType application/octet-stream .pdf
AddType application/octet-stream .zip
AddType application/octet-stream .mov


10. 修改文件類型– 下面的示例可以讓任何的文件都成為PHP那麼被服務器解釋。比如:myphp, cgi,phtml等。
ForceType application/x-httpd-php
SetHandler application/x-httpd-php


11. 阻止存取.htaccess 文件
# secure htaccess file

order allow,deny
deny from all


12. 保護服務器上的文件被存取
# prevent access of a certain fileorder allow,deny
deny from all

13. 阻止目錄瀏覽
# disable directory browsing
Options All -Indexes

14. 設置默認主頁
# serve alternate default index page
DirectoryIndex about.html


參考:

iis上的.htaccess文件ISAPI_Rewrite的安装及使用

htaccess语法教程-2011网络时代

RewriteRule-htaccess详细语法使用教程

2010年6月21日 星期一

RewriteRule flag list

RewriteRule Option
Significance
Description
I
Ignore case
The regular expression of the RewriteRule and any corresponding RewriteCond directives is performed using case-insensitive matching.(不分大小寫)
F
Forbidden(被禁止)
In case the RewriteRule regular expression matches, the web server returns a 404 Not Found response, regardless of the format string (second parameter of RewriteRule) specified. Read Chapter 4 for more details about the HTTP status codes.
L
Last rule
If a match is found, stop processing further rules.
N
Next iteration
Restarts processing the set of rules from the beginning, but using the current rewritten URL. The number of restarts is limited by the value specified with the RepeatLimit directive.
NS
Next iteration of the same rule
Restarts processing the rule, using the rewritten URL. The number of restarts is limited by the value specified with the RepeatLimit directive, and is calculated independently of the number of restarts counted for the N directive.
P
Proxy
Immediately passes the rewritten URL to the ISAPI extension that handles proxy requests. The new URL must be a complete URL that includes the protocol, domain name, and so on.
R
Redirect
Sends a 302 redirect status code to the client pointing to the new URL, instead of rewriting the URL. This is always the last rule, even if the L flag is not specified.
RP
Permanent redirect
The same as R, except the 301 status code is used instead.
U
Unmangle log
Log the new URL as it was the originally requested URL.
O
Normalize
Normalize the URL before processing by removing illegal characters, and so on, and also deletes the query string.
CL
Lowercase
Changes the rewritten URL to lowercase.
CU
Uppercase
Changes the rewritten URL to uppercase.