介紹常用的各種系統(tǒng)rewrite重寫規(guī)則方法,用來美化網(wǎng)頁的鏈接,提高搜索引擎收錄。
一.web.config 適用iis7以上
實例1:普通重寫.htaccess轉(zhuǎn)換web.config 注意: 1.添加<match url="^(.*/)* 2. 添加 url="{R:1} 3.去掉 list.asp\?teacher_id 轉(zhuǎn)義符
<?xml version="1.0" encoding="UTF-8"?>
       <configuration>
          <system.webServer>
             <rewrite>
                <rules>
                   <rule name="rule1">
                   <match url="^(.*)t/([0-9,a-z]*)" ignoreCase="false" />
                   <action type="Rewrite" url="{R:1}/t_list.asp?teacher_id={R:2}" appendQueryString="false" />
                   </rule>
                   <rule name="rule2">
                   <match url="^(.*/)*([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)\.html\?*(.*)$" />
                   <action type="Rewrite" url="{R:1}/index.php?moduleid={R:2}&catid={R:3}&itemid={R:4}&page={R:5}" />
                   </rule>
            </rules>
         </rewrite>
       </system.webServer>
   </configuration>
實例2:其他重寫功能
(1)301重定向
<rule name="301Redirect" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
     <add input="{HTTP_HOST}" pattern="^xxx.com$" />
 </conditions>
<action type="Redirect" url="http://www.xxx.com/{R:0}" redirectType="Permanent" />
</rule>
(2)取消目錄執(zhí)行權(quán)限
<rule name="rule1">
       <match url="uploads/(.*).(php|asp|aspx)$" ignoreCase="false" />
       <conditions logicalGrouping="MatchAll">
             <add input="%" pattern="^$" ignoreCase="false" negate="true" />
       </conditions>
       <action type="AbortRequest" />
</rule>
 
<rule name="Rule2">
      <match url="(.*).(asp)$" ignoreCase="false" />
      <action type="AbortRequest" />
</rule>
(3)屏蔽來源域名
<rule name="rule1" stopProcessing="true">
      <match url="^(.*)$" />
      <conditions>
            <add input="{HTTP_REFERER}" pattern="ylhqvip.com" negate="true" />
            <add input="{HTTP_REFERER}" pattern="^$" negate="true" />
      </conditions>
      <action type="AbortRequest" />
</rule>
(4)屏蔽ip地址
<rule name="band ip" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAny">
            <add input="%{HTTP_X_FORWARDED_FOR}&%{REMOTE_ADDR}&%{HTTP_X_Real_IP}" pattern="(8.8.4.4|8.8.8.)" />
      </conditions>
      <action type="AbortRequest" />
</rule>
(5)過濾靜態(tài)文件
<rule name="Imported Rule 1" stopProcessing="true">
      <match url="^(.*)$" ignoreCase="false" />
      <conditions logicalGrouping="MatchAll">
              <add input="{URL}" pattern="^.*(.css|.js|.gif|.png|.jpg|.jpeg|.xml)" ignoreCase="false" />
      </conditions>
      <action type="None" />
</rule>
(6)屏蔽蜘蛛
<rule name="Block spider" stopProcessing="true">
      <match url="(.*)" ignoreCase="false" negate="false" />
      <conditions>
           <add input="{HTTP_USER_AGENT}" pattern="baiduspider|googlebot" />
      </conditions>
      <action type="AbortRequest" />
</rule> 
語法總結(jié)
(1)<add>條件判斷,就像我們程序中的if語句一樣,表示如果符合某個或某幾個條件則執(zhí)行action后的語句
#判斷訪問域名:     <add input="{HTTP_HOST}" pattern="^www.xxx.com$" />                                                   
#判斷user_agent:   <add input="{HTTP_USER_AGENT}" pattern="baiduspider|googlebot" />                                      
#判斷訪問來源域名: <add input="{HTTP_REFERER}" pattern="xxx.com" negate="true" />
#判斷url中:        <add input="{URL}" pattern="^.*(.css|.js|.gif|.png|.jpg|.jpeg|.xml)" ignoreCase="false" />
#判斷url中?后參數(shù): <add input="{QUERY_STRING}" pattern="blog" negate="true" />                                            
#判斷url路徑地址:  <add input="{REQUEST_URI}" pattern="blog" negate="true" />   
#判斷ip(包括代理): <add input="%{HTTP_X_FORWARDED_FOR}&%{REMOTE_ADDR}&%{HTTP_X_Real_IP}" pattern="(8.8.4.4|8.8.8.)" />
#判斷真實文件:     <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" pattern="" ignoreCase="false" />      
#判斷真實目錄:     <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" pattern="" ignoreCase="false" /> 
#判斷match中的變量:<add input="{R:1}" pattern="^(bbs|blog)" ignoreCase="false" negate="true" />
#其他              <add input="%" pattern="^$" ignoreCase="false" negate="true" />
(2)<action>處理方式
#禁止訪問:         <action type="AbortRequest" />  
#重定向到          <action type="Redirect" url="http://www.xxx.com" redirectType="Permanent" />   
#重寫到            <action type="Rewrite" url="{R:1}/t_list.asp?teacher_id={R:2}" appendQueryString="false" />  
#不做操作          <action type="None" />
#向客戶端返回狀態(tài)  <action type="CustomResponse" statusCode="403" statusReason="Forbidden" statusDescription="Forbidden" />
(3)參數(shù)
忽略大小寫: ignoreCase="true"|ignoreCase="false" 非(不等于): negate="true" 不帶?后面的參數(shù): appendQueryString="false" 永久重定向: redirectType="Permanent" 匹配條件為所有還是一條: logicalGrouping="MatchAll"|logicalGrouping="MatchAny" # 用于conditions節(jié)點
二.htaccess 適用iis6(rewrite3.1)|linux
實例1:普通重寫
<IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteCond %{QUERY_STRING} ^(.*)$
      RewriteRule ^topic-(.+)\.html$ portal.php?mod=topic&topic=$1&%1
      RewriteCond %{QUERY_STRING} ^(.*)$
      RewriteRule ^article-([0-9]+)-([0-9]+)\.html$ portal.php?mod=view&aid=$1&page=$2&%1
      RewriteCond %{QUERY_STRING} ^(.*)$
      RewriteRule ^forum-(\w+)-([0-9]+)\.html$ forum.php?mod=forumdisplay&fid=$1&page=$2&%1
</IfModule>
 
RewriteRule ^(.*)/topic-(.+)\.html(\?(.*))*$ $1/portal\.php\?mod=topic&topic=$2&$4
RewriteRule ^(.*)/article-([0-9]+)-([0-9]+)\.html(\?(.*))*$ $1/portal\.php\?mod=view&aid=$2&page=$3&$5
RewriteRule ^(.*)/forum-(\w+)-([0-9]+)\.html(\?(.*))*$ $1/forum\.php\?mod=forumdisplay&fid=$2&page=$3&$5]
動態(tài)地址跳轉(zhuǎn)到靜態(tài)地址
RewriteRule ^goods-([0-9]+)(.*)\.html$  goods\.php\?id=$1 [QSA,L]
 
RewriteCond %{QUERY_STRING} ^id=([0-9]+)$ [NC]
RewriteRule ^goods.php$ /goods-%1.html? [L,R=301]
 
RewriteCond %{QUERY_STRING} ^id=1$ [NC]
RewriteRule ^category.php$ http://www.yaolongnonwoven.com/? [L,R=301] 加?不帶參數(shù),不加帶上參數(shù)
實例2:其他重寫功能
(1)301重定向
RewriteCond %{HTTP_HOST} ^xxxx1.com$ [NC] 
RewriteCond %{HTTP_HOST} ^xxxx2.com$ [NC] 
RewriteRule ^(.*)$ http://www.xxxx1.com/$1 [R=301,L]
(2)取消目錄執(zhí)行權(quán)限
RewriteCond % !^$ RewriteRule uploads/(.*).(php)$ – [F] RewriteRule data/(.*).(php)$ – [F]
(3)屏蔽來源域名
RewriteCond %{HTTP_REFERER} www.baidu.com [NC]
RewriteRule ^(.*)$ - [F]
(4)屏蔽ip地址
RewriteCond %{http:X-Forwarded-For}&%{REMOTE_ADDR}&%{http:X-Real-IP} (8.8.4.4|8.8.8.) [NC]
RewriteRule (.*) - [F]
(5)過濾靜態(tài)文件
RewriteCond %{REQUEST_URI} ^.*(.css|.js|.gif|.png|.jpg|.jpeg|.xml)
RewriteRule ^(.*)$   - [L] 
 
RewriteCond %{REQUEST_FILENAME} !-f     
RewriteCond %{REQUEST_FILENAME} !-d
(6)屏蔽蜘蛛
RewriteCond %{HTTP_USER_AGENT} (baiduspider|googlebot) [NC]
RewriteRule ^(.*)$ - [F]
語法總結(jié)
(1)RewriteCond條件判斷,就像我們程序中的if語句一樣,表示如果符合某個或某幾個條件則執(zhí)行RewriteCond下面緊鄰的
RewriteRule語句
#判斷訪問域名:     RewriteCond %{HTTP_HOST} ^xxxx.com$ [NC]                                                    
#判斷user_agent:   RewriteCond %{HTTP_USER_AGENT} Baiduspider [NC]                                  
#判斷訪問來源域名: RewriteCond %{HTTP_REFERER} www.baidu.com [NC]
#判斷METHOD:       RewriteCond %{REQUEST_METHOD} ^(TRACE|OPTIONS)
#判斷url中?后參數(shù): RewriteCond %{QUERY_STRING} ^id=([0-9]+)$ [NC]                                           
#判斷url路徑地址:  RewriteCond %{REQUEST_URI} ^/bbs    
#判斷ip(包括代理): RewriteCond %{http:X-Forwarded-For}&%{REMOTE_ADDR}&%{http:X-Real-IP} (8.8.4.4|8.8.8.) [NC]
#判斷真實文件:     RewriteCond %{REQUEST_FILENAME} !-f     
#判斷真實目錄:     RewriteCond %{REQUEST_FILENAME} !-d
#判斷header        RewriteCond %{HTTP:header}
#判斷以上所有情況: RewriteCond $1 !^(bbs|blog)
#其他 RewriteCond % !^$ 
(2)處理方式
#禁止訪問: RewriteRule (.*) - [F] #重定向到 RewriteRule ^(.*)$ http://www.xxx.com/404.html [R=301,L] #重寫到 RewriteRule ^goods-([0-9]+)(.*)\.html$ goods\.php\?id=$1 [QSA,L] #不做操作 RewriteRule ^(.*)$ - [L]參數(shù)解釋:
$N 規(guī)則后向引用
%N RewriteCond 后向引用
${mapname:key|default}
%{VARNAME} 服務(wù)器變量
‘!’ 取非
[C] 與下一個規(guī)則聯(lián)鎖
[CO=name:val:domain:lifetime:path] 設(shè)置cookie
[F] 強制禁止應(yīng)答
[G] 強制繼續(xù)應(yīng)答
[H=content-handler] 明確的內(nèi)容處理 (不適用)
[L] 上一個規(guī)則標記
[N] 再次應(yīng)用規(guī)則
[NC] 大小寫不敏感
[NE] 不轉(zhuǎn)義輸出
[NS]非內(nèi)部子請求
[P]代理通過
[QSA] 追加查詢字符串
[R =code] 重定向
[S=num] 跳到下面第n條規(guī)則
[T=MIME-type] 強制明確應(yīng)答 MIME 類型
RewriteCond
[NC] 大小寫不敏感
[OR] 邏輯并集
三.nginx 規(guī)則 
實例1.普通重寫
location / { 
    if (!-e $request_filename) { 
        rewrite  ^(.*)$  /index.php?s=$1  last; 
        break;   
    } 
}
實例2.其他重寫
(1).301重定向
server_name test.com www.test.com; 
if ($host ~* test.com) { 
    rewrite ^/(.*)$ http://www.test.com/$1 permanent; 
}
http跳轉(zhuǎn)https
普通
rewrite ^(.*) https://www.abc.com$1 permanent;
有cdn
if ( $http_from_https != 'on' ){
     rewrite ^(.*) https://www.abc.com$1 permanent;      
 }
(2). 取消目錄執(zhí)行權(quán)限
location ~* ^/(uploads|templets|data)/.*.(php|php5)$ {
                deny  all;
        }
(3).屏蔽來源域名
location / {
            valid_referers www.baidu.com www.#;
            if ($invalid_referer){
                    return 403;
            }
    }
防盜鏈
location ~* \.(gif|jpg|png|webp)$ {
   valid_referers none blocked domain.com *.domain.com server_names ~\.google\. ~\.baidu\.;
   if ($invalid_referer) {
    return 403;
    #rewrite ^/ http://www.domain.com/403.jpg;
   }
   root /opt/www/image;
  }
(4).屏蔽ip地址
allow 1.1.1.2;
allow all;
deny all;
deny 1.1.1.2
 
location ^~ /xxx/xxx/xx/
    {
      allow 172.0.0.1;
      allow xxx.xxx.0.0/8;#表示允許xxx.xxx.0.1 ~ xxx.xxx.255.254  
      allow xxx.0.0.0/16;#表示允許xxx.0.0.1 ~ xxx.255.255.254
      allow xxx.xxx.xxx.x; 
      deny all;
      }
前端還有cdn情況
map $http_x_forwarded_for  $clientIp {
        ""      $remote_addr;
        ~^(?P<firstAddr>[0-9\.]+),?.*$  $firstAddr;
}
if ($clientIp ~* "127.0.0.1|127.0.0.2") {
   return 403;
   break;
}
(5).屏蔽蜘蛛
if ($http_user_agent ~ "FeedDemon|JikeSpider|MJ12bot|heritrix|EasouSpider|LinkpadBot|Ezooms" )
{
  return 403;
}
(6).禁止非GET|HEAD|POST方式的抓取
if ($request_method !~ ^(GET|HEAD|POST)$) {
  return 403;
  }
語法總結(jié)
(1)RewriteCond條件判斷,就像我們程序中的if語句一樣,表示如果符合某個或某幾個條件則執(zhí)行RewriteCond下面緊鄰的RewriteRule語句
#判斷訪問域名:     if ($host ~* test.com)                                                   
#判斷user_agent:   if ($http_user_agent ~* "baiduspider" )                                
#判斷訪問來源域名: valid_referers www.baidu.com;if ($invalid_referer){return 403;}
#判斷METHOD:       if ($request_method !~ ^(GET|HEAD|POST)$)
#判斷url中?后參數(shù): if ($request_uri ~* ^/list.php\?([^_]+)(_[0-9]+)$)                                           
#判斷url路徑地址:  if ($uri ~* ^/list.php\?([^_]+)(_[0-9]+)$)    
#判斷ip:           if ($remote_addr ~* "127.0.0.1|127.0.0.2")
#判斷真實文件:     -e filename      
#判斷真實目錄:     -d filename
(2).處理方式
#禁止訪問: return 403; deny all; #重定向到 rewrite ^/(.*)$ http://www.test.com/$1 permanent; #重寫到 rewrite ^(.*)$ /index.php?s=$1 last; last – 基本上都用這個Flag。 break – 中止Rewirte,不在繼續(xù)匹配 redirect – 返回臨時重定向的HTTP狀態(tài)302 permanent – 返回永久重定向的HTTP狀態(tài)301 -f和!-f用來判斷是否存在文件 -d和!-d用來判斷是否存在目錄 -e和!-e用來判斷是否存在文件或目錄 -x和!-x用來判斷文件是否可執(zhí)行
參數(shù)解釋
location [=|~|~*|^~] /uri/ { … }
= 開頭表示精確匹配
^~ 開頭表示uri以某個常規(guī)字符串開頭,理解為匹配 url路徑即可。nginx不對url做編碼,因此請求為/static/20%/aa,可以被規(guī)則^~ /static/ /aa匹配到(注意是空格)。
~ 開頭表示區(qū)分大小寫的正則匹配
~* 開頭表示不區(qū)分大小寫的正則匹配
!~和!~*分別為區(qū)分大小寫不匹配及不區(qū)分大小寫不匹配 的正則
/ 通用匹配,任何請求都會匹配到。
全局變量
$args $content_length $content_type $document_root $document_uri $host $http_user_agent $http_cookie $limit_rate $request_body_file $request_method $remote_addr $remote_port $remote_user $request_filename $request_uri $query
建站咨詢熱線
029-33273980