nginx 基礎5 rewrite 重寫

1.開啓rewrite日誌

rewrite_log on; #http 段加入

error_log logs/xxxerror.log notice; #在將錯誤日誌級別調低

2.跳轉域名

 location / {
         rewrite / https://www.baidu.com;
        }

#表示,只要訪問這個域名直接跳轉到 baidu
nginx 基礎5 rewrite 重寫
#查看日誌能看到記錄用"/"訪問了"111.com",跳轉到了"baidu"
修改下代碼

location /rewrite/ {
         rewrite / https://www.baidu.com;
        }

#表示只有用域名後面跟着"/rewrite/",文件夾纔會跳轉(只有/rewrite/纔會觸發跳轉,其他文件夾正常轉發)
如下圖
nginx 基礎5 rewrite 重寫
#我這邊用"www.111.com/rewrite/123.com" 訪問才跳轉了

3.使用正則跳轉

例子1,
www.111.com/111/index.html 跳轉到 www.111.com/222/index.html

location / {
         rewrite ^/111/(.*)$  /222/$1 ;
        }

#"^"表示根的意思,就表示 www.111.com 的的意思,(.*) 匹配所有的意思,後面"$1"調用,
nginx 基礎5 rewrite 重寫
#日誌,能就看出/111/index.html 跳轉到 /222/index.html

4.rewrite指令

last    終止在本location塊中處理接收到的URI,並將此處重寫的URI作爲新的URI使用其他location進行處理,(轉到第1個location 匹配)
break   將此處重寫的URI作爲一個新的URI在當前location中繼續執行,並不會將新的URI轉向其他location。(繼續從當前的location 繼續往下匹配)
redirect    將重寫後的URI返回個客戶端,狀態碼是302,表明臨時重定向,主要用在replacement字符串不以“http://”,“ https://”或“ $scheme” 開頭;
permanent   將重寫的URI返回客戶端,狀態碼爲301,指明是永久重定向;
那麼什麼是永久性跳轉,什麼是臨時跳轉,這有什麼作用呢?下面我們舉例說明:

如果有一個url,/a。
如果配置成
rewrite "/a" "http://test.html" redirect;
則說明這個跳轉是一個臨時跳轉,此時如果有網絡爬蟲爬這個鏈接時,是不會更新自己的url數據庫的。
但是如果配置成permanet,則爬蟲會更新自己的url數據庫,把/a更新爲http://test.html。
這也就是臨時跳轉和永久跳轉的區別。
break和last區別測試
        location /222/ {
        rewrite ^/222/(.*) /333/$1;
}
        location / {
       rewrite ^/111/(.*) /222/$1 break;

}

#上面配置,最後url會輸出到"222"文件夾裏,如果把break 換成了last的話,url裏的111會被替換成222 從第一個location繼續匹配,這樣最終輸出url是"333"

#

5.if 判斷加調用變量跳轉

nginx 基礎5 rewrite 重寫
nginx 基礎5 rewrite 重寫
實例1

 if ($server_port = 80) {
            rewrite ^(.*)$ https://$host$1 permanent;
           }

#在http段配置,表示如果訪問者是以80端口訪問的,就執行跳轉。匹配根後面的url,重寫成https://"訪問的域名"+"匹配的url"

實例2

   if ( !-f $request_filename ){
   rewrite (.*) http://$host/bucunzai.html;
}

#在location 段配置,"! -f $request_filename" 表示,檢測url請求本地是否有問題,如果頁面文件不存在,就轉發給 "buzunzai.html".

實例3 www.111.com/jpg-aaa-bbb-ccc.html => www.111.com/jpg/aaa/bbb/ccc/jpg_ccc.html

        location / {
        rewrite ^/(.*)-(.*)-(.*)-(.*).html$ /$1/$2/$3/$4/$1_$4.html  ;
}

實例4 補全www

        if ($host = "111.com"){
        rewrite ^(.*)$ http://www.111.com$1 last;
}

#寫在http段,"$host" 變量就是 url裏的域名假如以 "111.com/123.html" 訪問就是
"111.com",假如以 "www.111.com/233.html" 就是"www.111.com"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章