Nginx之Rewrite重定向

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

常见的Nginx正则表达式
^匹配输入字符串的起始位置
$匹配输入字符串的结束位置
*匹配前面的字符零次或多次。如“ol*”能匹配“o”及“ol”、“oll”
+匹配前面的字符一次或者多次。如“ol+”能匹配"ol"及“oll”、"olll",但不能匹配“o”
?匹配前面的字符零次或一次例如“do(es)?”能匹配“do”或者“does”“”等效于“{01}”
.匹配除“\n”之外的任何单个字符若要匹配包括“\n”在内的任意字符请使用诸如“{.\n}”之类的模式
\将后面接着的字符标记为一个特殊字符或一个原义字符或一个向后引用如“\n”匹配一个换行符而“\$”则匹配“$”
\d匹配纯数字
{n}重复n次
{n,}:重复n次或更多次
{n,m}重复n到m次
[]定义匹配的字符范围
[c]匹配单个字符c
[a-z]匹配a-z小写字母的任意一个
[a-zA-Z0-9]匹配所有大小写字母或者数字任意一个
()表达式的开始和结束位置
|或运算符

URIUniform Resource Identifier统一资源标识符是一种字符串标识符用于标识抽象或物理资源
如文件、图片、视频等。

它由多个组件组成包括协议、主机名、端口号、路径等例如 http://www.kgc.com:8080/index.html 就是一个 URI。

在 Nginx 中匹配的对象通常是 URI 的一部分比如 /index.html、/images/logo.png 等。

location分类
1、精准匹配location = / {...}
2、一般匹配location / {...}
3、正则匹配location ~ / {...}

location常用的匹配规则
=进行普通字符精确匹配也就是完全匹配
^~表示普通字符匹配使用前缀匹配如果匹配成功就不再匹配其他的location
~区分大小写的匹配
~*:不区分大小写的匹配
!~区分大小写的匹配取非
!~*不区分大小写的匹配取非

location优先级
首先精确匹配 =
其次前缀匹配 ^~
其次是按文件中顺序的正则匹配~或者~*
然后匹配不带任何修饰的前缀匹配
最后是交给/通用匹配

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

www.ky30.com/   

www.ky30.com/index.html

www.ky30.com/documents/

www.ky30.com/images

www.ky30.com/a.jpg

http://www.example.com/gallery/images/cat.png
A)Location /gallery { }      
B)Location ~* /. (png|jpg)$ { }
C)Location = /gallery/images { }    
D)Location / { }

location实例说明
1location = / {}
=为精确匹配 / 主机名后面不能带任何字符串比如访问 / 和 /data则 / 匹配/data 不匹配
再比如 location = /abc则只匹配/abc /abc/匹配/abcd不匹配。若 location  /abc
则即匹配/abc 、/abcd/ 同时也匹配 /abc/。

2location / {}
因为所有的地址都以 / 开头所以这条规则将匹配到所有请求 比如访问 / 和 /data, 则 / 匹配 /data 也匹配
但若后面是正则表达式会和最长字符串优先匹配最长匹配


3location ^~ /test {}
匹配任何以 /images/ 开头的地址
location ^~ /test {
    root html;
    index index.htm index.html;

  }

 location ^~ /test/abc {
    root html;
    index index.htm index.html;
 }

4location ~* \.(gif|jpg|jpeg)$ {}
匹配所有以 gif、jpg或jpeg 结尾的请求
然而所有请求 /images/ 下的图片会被 location ^~ /images/ 处理因为 ^~ 的优先级更高所以到达不了这一条正则
#不区分大小写
location ~* /TEST {
   root html;
   index index.htm index.html;

location = /1.jpg {
root /data/nginx/static1;
}

location /1.jpg {
root /data/nginx/static2;
}

location ~* \.(gif|jpg|js)$ {
root /data/nginx/static3;
}


优先级总结
location = 完整路径> location ^~ 完整路径>location ~~* 正则顺序 > location 部分起始路径 > location /


在实际网站中使用的匹配规则至少有三个匹配规则
#第一个必选规则
直接匹配网站根通过域名访问网站首页比较频繁使用这个会加速处理比如说官网。
可以是个静态首页可以直接转发给后端应用服务器
location = / {
   root  html;
   index index.html index. htm;
}

#第二个必选规则是处理静态文件请求这是nginx作为http服务器的强项
有两种配置模式目录匹配或后缀匹配,任选其一或搭配使用
location ^~ /static/ {
    root /webroot/static/;
}

location ~* \.(html|gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}

#第三个规则就是通用规则比如用来转发带.php、.jsp后缀的动态请求到后端应用服务器
非静态文件请求就默认是动态请求
location / {
    proxy_pass http://tomcat_server;
}


rewrite简介
1、rewrite作用
rewrite作用就是使用nginx提供的全局变量或自己设置的变量结合正则表达式和标志位实现url重写以及重定向。
比如更换域名后需要保持旧的域名能跳转到新的域名上、某网页发生改变需要跳转到新的页面网站防盗链等等需求
rewrite只能放在server{},location{},if{}中并且默认只能对域名后边的除去传递的参数外的字符串起作用
例如 http://www.kgc.com/a/we/index.php?id=1&u=str 只对/a/we/index.php重写。

nginx的内置变量
$uri: 请求的URI不包含主机和查询参数。

$request_uri: 请求的URI包含主机和查询参数。

$args: 查询参数部分即?后面的内容。

$query_string: 整个查询字符串包含?。

$host: 请求的主机名。

$http_user_agent: 请求的User-Agent头信息用于表示请求的客户端浏览器和操作系统。

$http_referer: 请求的Referer头信息表示当前页面的来源URL。

$remote_addr: 客户端的IP地址。

$remote_port: 客户端的端口号。

$server_addr: 服务器的IP地址。

$server_port: 服务器的端口号。

$request_method: 请求的HTTP方法如GET、POST、等。

$content_type: 请求的Content-Type头信息表示请求体的MIME类型。

$content_length: 请求的Content-Length头信息表示请求体的长度。

$scheme: 请求的协议通常是http或https。

$request_filename: 请求的文件名用于指定请求的实际文件路径。

$document_root: 当前请求的根目录。

$server_name: 服务器名称用于匹配server块的server_name指令。
x_forwarded_for:用于获取HTTP请求头中的X-Forwarded-For字段的值。
X-Forwarded-For是一个常见的HTTP请求头通常由代理服务器添加用于指示原始客户端的IP地址。
proxy_set_header X-Forwarded-For $remote_addr; 这个是传给后端。

X-Real-IP头部为客户端真实IP地址
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header指令来设置X-Real-IP头部的值为$remote_addr即客户端的真实IP地址。
这样Nginx会将客户端的真实IP地址作为X-Real-IP头部的值传递给后端服务器。

 location / {
            root   html;
            index  index.html index.htm;
            default_type text/plain;#表示如果没有在其他地方显示设置content-type的头字段默认响应为text/plain纯文本格式
            return 200 "way:$request_method";
        }


2、rewrite跳转实现
Nginx通过ngx_http_rewrite_module模块支持URL重写、支持if条件判断但不支持else
跳转从一个location跳转到另一个location循环最多可以执行10次超过后nginx将返回500错误
PCRE支持perl兼容正则表达式的语法规则匹配
重写模块set指令创建新的变量并设其值

3、rewrite执行顺序如下
执行 server 块里面的 rewrite 指令。
执行 location 匹配。
执行选定的 location 中的 rewrite 指令。

4、rewrite语法
rewrite <regex> <replacement> [flag]
regex 表示正则匹配规则。
replacement 表示跳转后的内容。
flag 表示 rewrite 支持的 flag 标记。

5、flag标记说明
last 本条规则匹配完成后继续向下匹配新的location URI规则。
break 本条规则匹配完成即终止不再匹配后面的任何规则且URI不会发生变化。
redirect 返回302临时重定向浏览器地址会显示跳转后的URL地址。
permanent 返回301永久重定向浏览器地址栏会显示跳转后的URL地址。

permanent:
location / {

        rewrite /test/(.*) /ky30/$1 permanent;
        index index.html index.htm;

        }
        
mkdir test 
echo test > index.html
mkdir ky30
echo ky30 > index.html
返回301,永久重定向

redirect
location / {

        rewrite /test/(.*) /ky30/$1 redirect;
        index index.html index.htm;

        }
返回302,临时重定向

永久重定向301用于永久性的URL变更搜索引擎会转移权重和排名到新的URL客户端会记住新的URL。

临时重定向302用于短期的URL变更搜索引擎不会转移权重和排名到新的URL客户端会继续访问原始URL。

break
location / {

        rewrite /test/(.*) /ky30/$1 break;
        index index.html index.htm;

        }
也会跳转uri没有发生变化而且只会请求一次。

last:
  location /test1 {
         index index.html index.htm;
         rewrite /test1/(.*) /test2/$1 last;
        }

        location /test2 {
        index index.html index.htm;
        rewrite /test2/(.*) /test1/$1 last;

        }

        location /break {
        rewrite /break/(.*) /test1/$1 break;
        rewrite /test1/(.*) /test2/$1 break;
        index index.html index.htm;
        }

        location /last {
        rewrite /last/(.*) /test1/$1 last;
        rewrite /test1/(.*) /test2/$1 last;
        index index.html index.htm;
        }
"rewrite or internal redirection cycle while processing"是Nginx中的一个错误信息
它表示在处理请求时发生了重写或内部重定向循环。

这个错误通常是由于配置文件中的重写规则导致了一个无限循环。当Nginx进行重写或内部重定向时
如果新的URI再次匹配了原始的重写规则就会产生循环并导致错误。

last:循环最多可以执行10次超过后nginx将返回500错误


总结从功能看rewrite和location似乎有点像都能实现跳转主要区别在于rewrite是在同一域名内更改获取资源的路径
而 location是对一类路径做控制访问或反向代理还可以proxy_pass 到其他机器。

基于域名的跳转
现在公司旧域名www.kgc.com有业务需求变更需要使用新域名www.benet.com代替但是旧域名不能废除
需要跳转到新域名上而且后面的参数保持不变。

vim /usr/local/nginx/conf/nginx.conf
server {
    listen       80;
    server_name  www.kgc.com;                                       #域名修改    
    #charset utf-8;
    #access_log  /var/log/nginx/kgc.com-access.log;                  #日志修改
    location / {
    #添加域名重定向
        if ($host = 'www.kgc.com'){                                #$host为rewrite全局变量代表请求主机头字段或主机名
            rewrite ^/(.*)$ http://www.benet.com/$1 permanent;       #在重定向时$1表示请求的URL
        }
        root   html;
        index  index.html index.htm;
    }
}

echo "192.168.233.61 www.kgc.com www.benet.com" >> /etc/hosts
systemctl restart nginx

permanent
permanent: 永久性重定向请求日志中的状态码为301。


基于客户端IP访问跳转
今天公司业务新版本上线要求所有 IP 访问任何内容都显示一个固定维护页面
只有公司 IP 192.168.233.61访问正常。
vim /usr/local/nginx/conf/nginx.conf
server {
    listen       80;
    server_name  www.kgc.com;                       #域名修改    
    charset utf-8;
    access_log  /var/log/nginx/kgc.com-access.log;  #日志修改

    #设置是否合法的IP标记
    set $rewrite true;                             #设置变量$rewrite变量值为boole值true
    
    #判断是否为合法IP
    if ($remote_addr = "192.168.233.61"){          #当客户端IP为192.168.233.61时将变量值设为false不进行重写
        set $rewrite false;
    }
                                                   #除了合法IP其它都是非法IP进行重写跳转维护页面
    if ($rewrite = true){                          #当变量值为true时进行重写
        rewrite (.+) /error.html;                   #重写在访问IP后边插入/error.html例如192.168.233.22/error.html
    }
    location = /error.html {
        root html;                                 #网页返回html/error.html的内容
    }
    
    location / {
        root   html;
        index  index.html index.htm;
    }
}

systemctl restart nginx

只有 IP 为 192.168.233.61 能正常访问其它地址都是维护页面

systemctl restart nginx.service 


基于目录下所有 php 结尾的文件跳转
vim /usr/local/nginx/conf/nginx.conf
server {
    listen       80;
    server_name  www.test.com;        #域名修改    
    charset utf-8;
    access_log  /var/log/nginx/www.test.com-access.log;
    
    location ~* /upload/.*\.php$ {
        rewrite (.+) http://www.test.com permanent;
    }
 
    location / {
        root   html;
        index  index.html index.htm;
    }
}
systemctl restart nginx

访问http://www.test.com/upload/123.php直接跳转到www.test.com

官网地址 https://nginx.org/en/docs/http/ngx_http_core_module.html#location


 

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: nginx