Nginx Rewrite常用写法
1、功能www.example.com/123.php --> www.example.com/123.html
location / {
root html;
index index.php index.html index.htm;
rewrite /(.*)\.php$ /$1.html break;
}
2、功能:www.example.com/123.php --> www.example.com/123.html -->www.example.com/123.txt
location / {
root html;
index index.php index.html index.htm;
rewrite /(.*)\.php$ /$1.html last;
rewrite /(.*)\.html$ /$1.txt break;
}
3、功能:访问不存或者已经删除页面跳转到指定页面(none.html)
location / {
root html;
index index.php index.html index.htm;
if (!-f $request_filename){
rewrite ^/(.*)$ /none.html break;
}
}
4、功能:盗链 www.example.com/jd.html -->https://www.jd.com
vi jd.html
5、功能:防盗链 www.123123.com/example.html -->https://www.example.com -->404
location / {
root html;
index index.php index.html index.htm;
valid_referers none blocked www.example.com;
if ($invalid_referer){
return 404;
}
6、功能:防盗链 www.123123.com/example.html -->https://www.example.com -->https://www.jd.com/
location / {
root html;
index index.php index.html index.htm;
valid_referers none blocked www.example.com;
if ($invalid_referer){
#return 404;
rewrite ^/ https://www.jd.com/;
}
}
7、功能:http://www.example.com/1/1.html -->http://www.example.com/2/2.html
location /1{
rewrite .* /2/2.html permanent;
}
8、功能:http://www.example.com/2017/a.html -->http://www.example.com/2018/a.html (目录结构相同的情况下可以使用)
location /2017{
rewrite ^/2017/(.*)$ /2018/$1 permanent;
}
9、功能:http://www.example.com/2017/jd.html --> http://www.jd.com
location /2017{
if ($host ~* wwww.example.com){
rewrite .* http://www.jd.com permanent;
}
}
10、功能:http://www.example.com/zh_int/phones -->https://www.nokia.com/zh_int/phones(两个网站目录结构相同的情况下可以使用)
location /zh_int{
if ($host ~* wwww.example.com){
rewrite .* https://nokia.com/$request_uri permanent;
}
}
11、功能:http://www.example.com/login/baidu.html -->http://wwww.example.com/reg/login.php?user=baidu
location /login{
rewrite ^/login/(.*)\.html$ /reg/login.php?user=$1 permanent;
}
12、功能:http://www.example.com/date/2018-04-29.html -->http://www.example.com/date/2018/04/29.html
location /date{
rewrite ^/date/([0-9]+)-([0-9]+)-([0-9]+)\.html /date/$1/$2/$3.html permanent;
}
13、功能:http://jack.example.com ==> http://www.example.com/jack(域名需要配置泛解析)
location / {
root html;
index index.php index.html index.htm;
if ($host ~* "www.example.com$"){
break;
}
if ($host ~* "^(.*)\.example\.com$"){
set $user $1;
rewrite .* http://www.example.com/$user permanent;
}
}