Nginx Rewrite重写技术
Rewrite语法:
# {重写类型}:last、break、redirect、permanent
rewrite {规则} {定向路径} {重写类型}
rewrite ^/(.*) http://www.test.com/$1 permanent;
Rewrite重写类型:
last 相当于Apache里的[L]标记,表示完成rewrite
break 本条规则匹配完成后,终止匹配,不再匹配后面的规则
redirect 返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent 返回301永久重定向,浏览器地址会显示跳转后URL地址
Rewrite实例:
1.当访问http://106.52.36.65/1024.html 重定向到 http://106.52.36.65/index.php?id=1024
location / {
# 当访问根目录下的1024.html文件时跳转访问index.php?id=1024文件
rewrite ^/(\d+)\.html$ /index.php?id=$1 redirect;
# rewrite ^/(\d+)\.html$ /index.php?id=$1 break;
}
curl http://106.52.36.65/1024.html -L
返回结果:
C:\Users\v_lysvliu>curl http://106.52.36.65/1024.html -L
<pre>Array
(
[id] => 1024
)
C:\Users\v_lysvliu>
2.当访问http://106.52.36.65/home/1024.html 重定向到 http://106.52.36.65/index.php?id=1024
location / {
rewrite ^/home/(\d+)\.html$ /index.php?id=$1 redirect;
}
3.当访问http://106.52.36.65/admin/1024.html 重定向到 http://106.52.36.65/admin/index.php?id=1024
location / {
rewrite ^/(\w+)/(\d+)\.html$ /$1/index.php?id=$2 redirect;
}
4.当访问http://106.52.36.65/home/12-31-2020.html 重定向到 http://106.52.36.65/home/index.php?id=2020-12-31
id=2020-12-31
location / {
# (\w+)/ == home/ (\d+)-(\d+)-(\d+)\.html == 12-31-2020.html
rewrite ^/(\w+)/(\d+)-(\d+)-(\d+)\.html$ /$1/index.php?id=$4-$2-$3 redirect;
}
- 当访问http://106.52.36.65 重定向到 http://www.baidu.com
location / {
rewrite .* http://www.baidu.com permanent;
}
6.当访问http://106.52.36.65:80 重定向到 http://106.52.36.65:443
location / {
if ($server_port ~* 80) {
rewrite .* http://106.52.36.65:443 permanent;
#rewrite .* http://$host:443 permanent;
}
}