rewirte
规则也称为规则重写,主要功能是实现浏览器访问HTTP URL
的跳转,其正则表达式是基于Perl
语言。通常而言,几乎所有的Web
服务器均可以支持URL
重写。rewrite URL
规则重写的用途如下:
Nginx rewrite
规则使用中有3个概念,分别是rewrite
结尾标识符、rewrite
规则常用表达式、Nginx rewrite
变量,3个概念的详解如下:
HTTP headers
:HTTP_USER_AGENT
,HTTP_REFERER
,HTTP_COOKIE
,HTTP_HOST
,HTTP_ACCEPT
connection & request
:REMOTE_ADDR
,QUERY_STRING
server internals
:DOCUMENT_ROOT
,SERVER_PORT
,SERVER_PROTOCOL
system stuff
:TIME_YEAR
,TIME_MON
,TIME_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;