首頁技術(shù)文章正文

Rewrite命令的用法介紹【Nginx教程】

更新時間:2021-08-27 來源:黑馬程序員 瀏覽量:

rewrite指令

rewrite指令該指令通過正則表達(dá)式的使用來改變URI??梢酝瑫r存在一個或者多個指令,按照順序依次對URL進(jìn)行匹配和處理。

語法 rewrite regex replacement [flflag];
默認(rèn)值
位置

server、location、if

regex:用來匹配URI的正則表達(dá)式

replacement:匹配成功后,用于替換URI中被截取內(nèi)容的字符串。如果該字符串是以"http://"或者"https://"開頭的,則不會繼續(xù)向下對URI進(jìn)行其他處理,而是直接返回重寫后的URI給客戶端。

flag:用來設(shè)置rewrite對URI的處理行為,可選值有如下:

·last:終止繼續(xù)在本location塊中處理接收到的URI,并將此處重寫的URI作為一個新的URI,使用各location塊進(jìn)行處理。該標(biāo)志將重寫后的URI重寫在server塊中執(zhí)行,為重寫后的URI提供了轉(zhuǎn)入到其他location塊的機會

location rewrite {
	rewrite ^/rewrite/(test)\w*$ /$1 last;
	rewrite ^/rewrite/(demo)\w*$ /$1 last;
}
location /test{
	default_type text/plain;
	return 200 test_success;
}
location /demo{
	default_type text/plain;
	return 200 demo_success;
}

訪問 http://192.168.200.133:8081/rewrite/testabc ,能正確訪問

rewrite指令用法

·break:將此處重寫的URI作為一個新的URI,在本塊中繼續(xù)進(jìn)行處理。該標(biāo)志將重寫后的地址在當(dāng)前的location塊中執(zhí)行,不會將新的URI轉(zhuǎn)向其他的location塊。

location rewrite {
	#/test /usr/local/nginx/html/test/index.html
	rewrite ^/rewrite/(test)\w*$ /$1 break;
	rewrite ^/rewrite/(demo)\w*$ /$1 break;
}
location /test{
	default_type text/plain;
	return 200 test_success;
}
location /demo{
	default_type text/plain;
	return 200 demo_success;
}

訪問 http://192.168.200.133:8081/rewrite/demoabc ,頁面報404錯誤

rewrite指令02

·redirect:將重寫后的URI返回給客戶端,狀態(tài)碼為302,指明是臨時重定向URI,主要用在replacement變量不是以"http://"或 者"https://"開頭的情況。

location rewrite {
	rewrite ^/rewrite/(test)\w*$ /$1 redirect;
	rewrite ^/rewrite/(demo)\w*$ /$1 redirect;
}
location /test{
	default_type text/plain;
	return 200 test_success;
}
location /demo{
	default_type text/plain;
	return 200 demo_success;
}

訪問http://192.168.200.133:8081/rewrite/testabc請求會被臨時重定向,瀏覽器地址也會發(fā)生改變

·permanent:將重寫后的URI返回給客戶端,狀態(tài)碼為301,指明是永久重定向URI,主要用在replacement變量不是以"http://"或 者"https://"開頭的情況。

location rewrite {
	rewrite ^/rewrite/(test)\w*$ /$1 permanent;
	rewrite ^/rewrite/(demo)\w*$ /$1 permanent;
}
location /test{
	default_type text/plain;
	return 200 test_success;
}
location /demo{
	default_type text/plain;
	return 200 demo_success;
}

訪問http://192.168.200.133:8081/rewrite/testabc請求會被永久重定向,瀏覽器地址也會發(fā)生改變

rewrite_log指令

該指令配置是否開啟URL重寫日志的輸出功能。

語法 rewrite_log on|off;
默認(rèn)值 rewrite_log off;
位置 

http、server、location、if

開啟后,URL重寫的相關(guān)日志將以notice級別輸出到error_log指令配置的日志文件匯總。

rewrite_log on;
error_log logs/error.log notice;

將本頁面鏈接發(fā)送給QQ:435946716,免費獲取上面課程全套視頻、筆記和源碼。



猜你喜歡:

Nginx rewrite常用全局變量詳細(xì)介紹

Nginx配置server_name詳細(xì)教程

如何配置Nginx為系統(tǒng)服務(wù)?

Nginx升級教程:兩種方案任你選

黑馬程序員java開發(fā)培訓(xùn)課程

分享到:
在線咨詢 我要報名
和我們在線交談!