1. nginx的地址重写rewrite
1. URL Rewrite最常见的应用是URL伪静态化,是将动态页面显示为静态页面方式的一种技术。
2. 从安全角度上讲,如果在URL中暴露太多的参数,无疑会造成一定量的信息泄漏
3. 实现网站地址跳转,例如用户访问360buy.com,将其跳转到jd.com
rewrite相关指令有 if、rewrite、set、return
if (condition) { … }
if 可以支持如下条件判断匹配符号
~ 正则匹配 (区分大小写)
~* 正则匹配 (不区分大小写)
!~ 正则不匹配 (区分大小写)
!~* 正则不匹配 (不区分大小写)
-f 和!-f 用来判断是否存在文件
-d 和!-d 用来判断是否存在目录
-e 和!-e 用来判断是否存在文件或目录
-x 和!-x
Rewrite flag
rewrite 指令根据表达式来重定向URI,或者修改字符串。可以应用于server,location, if环境下每行rewrite指令最后跟一个flag标记,支持的flag标记有:
last 相当于Apache里的[L]标记,表示完成rewrite。默认为last。
break 本条规则匹配完成后,终止匹配,不再匹配后面的规则
redirect 返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent 返回301永久重定向,浏览器地址会显示跳转后URL地址
例子
本地解析host文件
# http://www.testpm.com/a/1.html ==> http://www.testpm.com/b/2.html
location /a {
root /html;
index 1.html index.htm;
rewrite .* /b/2.html permanent;
}
location /b {
root /html;
index 2.html index.htm;
}
例2:
# http://www.testpm.com/2019/a/1.html ==> http://www.testpm.com/2018/a/1.html
location /2019/a {
root /var/www/html;
index 1.html index.hml;
rewrite ^/2019/(.*)$ /2018/$1 permanent;
}
location /2018/a {
root /var/www/html;
index 1.html index.htl;
}
例
# http://www.qf.com/a/1.html ==> http://jd.com/a/1.html
location /a {
root /html;
if ( $host ~* testpm.com ){
rewrite .* http://jd.com$request_uri permanent;
}
}
例5: 在访问目录后添加/ (如果目录后已有/,则不加/)
# http://www.tianyun.com/a/b/c ==> http://www.tianyun.com/a/b/c/
# $1: /a/b
# $2: c
# http://$host$1$2$3/
location /a/b/c {
root /usr/share/nginx/html;
index index.html index.hml;
if (-d $request_filename) {
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
}
例6:
# http://www.tianyun.com/login/tianyun.html ==> http://www.tianyun.com/reg/login.html?user=tianyun
location /login {
root /usr/share/nginx/html;
rewrite ^/login/(.*)\.html$ http://$host/reg/login.html?user=$1;
}
location /reg {
root /usr/share/nginx/html;
index login.html;
}
2. return指令
例 如果访问的.sh结尾的文件则返回403操作拒绝错误
server {
listen 80;
server_name www.testpm.cn;
#access_log /var/log/nginx/http_access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location ~* \.sh$ {
return 403;
}
}
例 80 ======> 443 :80转443端口
server {
listen 80;
server_name www.chaosaigc.com;
access_log /var/log/nginx/http_access.log main;
return 301 https://www.chaosaigc.com$request_uri;
}
3. localtion指令
/ 通用匹配,任何请求都会匹配到
@ 内部服务跳转
(1) =:表示完全匹配;
(2) ^~:匹配URI的前缀,并且后面的正则表达式不再匹配,如果一个URI同时满足两个规则的话,匹配最长的规则;
(3) ~:匹配正则表达式,大小写敏感;
(4) ~*:匹配正则表达式,大小写不敏感;
优先级:(1)> (2) > (3) = (4)
@ :定义命名 location 区段,这些区段客户段不能访问,只可以由内部产生的请求来访问,如try_files或error_page等
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html;
try_files /index.htm /a.html /b.html @error;
}
location @error {
return 409;
}
}
4. nginx错误页面配置
error_page 404 403 500 502 503 504 /404.html;
location = /404.html {
root /usr/local/nginx/html;
}