
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_ACCEPTconnection & request:REMOTE_ADDR,QUERY_STRINGserver internals:DOCUMENT_ROOT,SERVER_PORT,SERVER_PROTOCOLsystem 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;