Nginx rewrite规则详解

TrumanWong
11/25/2021
TrumanWong

rewirte规则也称为规则重写,主要功能是实现浏览器访问HTTP URL的跳转,其正则表达式是基于Perl语言。通常而言,几乎所有的Web服务器均可以支持URL重写。rewrite URL规则重写的用途如下:

Nginx rewrite规则使用中有3个概念,分别是rewrite结尾标识符、rewrite规则常用表达式、Nginx rewrite变量,3个概念的详解如下:

其中last和break用来实现URL重写时,浏览器地址栏URL地址不变。HTTP headersHTTP_USER_AGENTHTTP_REFERERHTTP_COOKIEHTTP_HOSTHTTP_ACCEPTconnection & requestREMOTE_ADDRQUERY_STRINGserver internalsDOCUMENT_ROOTSERVER_PORTSERVER_PROTOCOLsystem stuffTIME_YEARTIME_MONTIME_DAY详解如下:

以下展示一些Nginx rewrite常见案例:

if ($host = 'trumanwl.com') {
    rewrite ^/(.*)$	https://www.trumanwl.com/$1	permanent;
}
rewrite	^/blog/1$	/newindex.html	last;
if ($host != 'www.trumanwl.com') {
    rewrite	^/(.*)$	https://www.trumanwl.com/$1 permanent;
}
if (! -e $request_filename) {
    rewrite	^/(.*)$	/index.php	last;
}
rewrite	^/(.+)/(\d+)	/$1?id=$2	last;
if ($http_user_agent ~ MSIE) {
    rewrite	^(.*)$	/ie/$1 break;
}
location ~ .*\.(sh|sql|env)$ {
    return 403;
}
if ($http_user_agent ~* "(Android)|(iPhone)|(Mobile)|(WAP)|(UCWEB)") {
    rewrite ^(.*)/$	https://m.trumanwl.com/	permanent;
}
if ($args ~* id=1) {
    return 403;
}
rewrite ^/([0-9])/comment/(.+)$	/index.php?id/$1/comment_id=$2	last;