Rewrite


Rewrite

 

Rewrite簡介

  Rewrite主要實現url地址重寫,以及重定向,就是把傳入web的請求重定向到其他url的過程

 

Rewrite基本概述

  1.地址跳轉,用戶訪問www.linux.com這個URL是,將其定向至一個新的域名www.baidu.com。

  2.協議跳轉,用戶通過http協議請求網站時,將其重新跳轉至https協議方式。

  3.偽靜態,將動態頁面顯示為靜態頁面方式的一種技術,便於搜索引擎的錄入,同時建上動態URL地址對外暴露過多的參數,提升更高的安全性。

  4.搜索引擎,SEO優化依賴於url路徑,好記的url便於搜索引擎錄入。

 

rewrite語法

  Syntax    : rewrite regex replacement [flag];

  Default    : —

  Context  : server, location, if

    rewrite         # 模塊命令

    regex         # 請求的鏈接(支持正則表達式)

    replacement     # 跳轉的鏈接

    [flag];      # 標簽

location /download/ {
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  break;
    return  403;
}

 

Rewrite標記Flag

  rewrite指令根據表達式來重定向URL,或者修改字符串,可以應用於server,location,if環境下,每行rewrite指令最后跟一個flag標記,支  持的flag標記有如下表格所示:

 

 

  last和break的區別

server {
    server_name _;
    listen 80;
    location ~ ^/break {
        rewrite (.*) /test break;
    }

    location ~ ^/last {
        rewrite (.*) /test last;
    }

    location /test {
        default_type text/html;
        return 200 "test";
    }
}

    break請求:

      1.請求linux.rewrite.com/break

      2.匹配 location ~ ^/break 會跳轉到 linux.rewrite.com/test

      3.請求跳轉后,回去查找本地站點目錄下的 /test

      4.如果找到了,則返回/code/test/index.html的內容;

      5.如果沒找到該目錄則報錯404,如果找到該目錄沒找到對應的文件則403

 

    last請求:

      1.請求linux.rewrite.com/last

      2.匹配 location ~ ^/last 會跳轉到 linux.rewrite.com/test

      3.如果找到了,則返回/code/test/index.html的內容;

      4.如果沒有找到,會重新對當前server發起請求,這個時候訪問地址就變成 linux.rewrite.com/test

      5.重新請求server會匹配到 location /test/ 直接返回該location的內容

      6.如果也沒有location匹配,再返回404;

 

  redirect和permanent的區別

location /redirect {
    rewrite (.*) http://www.baidu.com redirect;
}
location /permanent {
    rewrite (.*) http://www.baidu.com permanent;
}

  重定向 

    redirect:

      每次請求都會詢問服務器,如果當服務器不可用時,則會跳轉失敗。

 

    permanent:

      第一次請求會詢問,瀏覽器會記錄跳轉的地址,第二次則不再詢問服務器,直接通過瀏覽器緩存的地址跳轉。

 


免責聲明!

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



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