温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Nginx Rewrite的实现原理和使用方法

发布时间:2020-06-16 15:06:11 来源:亿速云 阅读:377 作者:元一 栏目:系统运维

一、理论讲解

1.1Nginx Rewrite简介

Nginx Rwrite即Nginx服务的规则重写,主要的功能是实现浏览器访问HTTP URL的跳转,其中相关的正则表达式是基于Perl语言。一般来说,几乎所有的Web服务器都支持URL重写。

Rewrite是一种服务器的重写 技术,它可以使得服务器可以支持 URL 重写,是一种最新流行的服务器技术。它还可以实现限制特定IP访问网站的功能。很多情况下,某个 IP 的访问很容易造成 CPU 100% (比如 某些搜索引擎的固定抓取,别人大量的采集站点),这个时候我们就要利用一些有效的手段封掉对方的 IP,让他无法消耗服务器的资源,封 IP 的方法有很多种,如果你的 Web 服务器安装了 Rewrite 模块的话,也可以试试利用 Rewrite 规则封掉对方的 IP。

1.1.1什么是URL?

对于百度给出的定义如下:URL(Uniform Resource Locator),统一资源定位符。这样的表述似乎过于抽象,因为可能根本不了解什么是“统一资源定位符”?其实我们可以将URL简易地理解为你所需要通过网络获取资源的地址,(URL)是由一串字符组成,这些字符可以是字母,数字和特殊符号。

具体实例如下:

php+HTML
http://www.wangluopx.cn/yunwei/gz/zz/2018-07-03/1940.html

其具体结构在这就不做详细阐述了,有兴趣可以自行查阅相关文档。

1.1.2“跳转”有什么用?

跳转需要根据具体的应用场景才能真正体会到nginx规则重写实现网页跳转的作用。稍后会根据不同的应用场景进行对应的操作与设置。一般来说,实现跳转的作用可以总结为以下几个方面:

  1. 调整用户浏览的URL,使其规范;
  2. 使搜索引擎收录网站内容,提升用户的使用体验;
  3. 隐藏网站URL真实地址等;

1.1.3Perl是什么语言?

Perl,一种功能丰富的计算机程序语言,运行在超过100种计算机平台上,适用广泛,从大型机到便携设备,从快速原型创建到大规模可扩展开发。

Perl借取了C、sed、awk、shell脚本语言以及很多其他程序语言的特性,其中最重要的特性是它内部集成了正则表达式的功能,以及巨大的第三方代码库CPAN。简而言之,Perl像C一样强大,像awk、sed等脚本描述语言一样方便,被Perl语言爱好者称之为“一种拥有各种语言功能的梦幻脚本语言”、“Unix中的王牌工具”。

1.2如何实现Rewrite跳转?

rewrite使用Nginx全局变量或自己设置的变量,结合正则表达式和标志位实现URL重写以及重定向
,基于ngx_http_rewrite_module模块进行处理。

1.2.1Rwrite 实用场景

Nginx跳转需求的实现方式

●使用rewrite进行匹配跳转
  ●使用if匹配全局变量后跳转
  ●使用location匹配再跳转

rewrite放在server{},if{},location{}段中

对域名或参数字符串

●使用if全局变量匹配
  ●使用proxy_ pass反向代理

1.2.2命令语法

rewrite <regex> <replacement> [flag];
正则  跳转后的内容  rewrite支持的flag

1.2.3location分类

location = patt{}[精准匹配]
location patt{} [一般匹配]
location ~patt{} [正则匹配]
正则匹配的常用表达式

标记                         说明
~           执行一个正则匹配,区分大小写
~          执行一个正则匹配,不区分大小写
!~          执行一个正则匹配,区分大小写不匹配
!~
        执行一个正则匹配,不区分大小写不匹配
^~          普通字符匹配;使用前缀匹配。如果匹配成功,则不再匹配其他location
=           普通字符精确匹配。也就是完全匹配
@           定义一个命名的location,使用在内部定向时

1.2.4location优先级

1.相同类型的表达式,字符串长的会优先匹配
2.按优先级排列
●=类型
●^~类型表达式
●正则表达式(~和~*)类型
●常规字符串匹配类型,按前缀匹配
●通用匹配(/) ,如果没有其它匹配,任何请求都会匹配到

1.2.5比较rewrite和location

1.相同点
●都能实现跳转
2.不同点
●rewrite是在同一域名内更改获取资源的路径
●location是对一类路径做控制访问或反向代理,还可以proxy_ pass
到其他机器
3.rewrite会写在location里,执行顺序:
●执行server块里面的rewrite指令
●执行location匹配
●执行选定的location中的rewrite指令

1.2.6location优先级规则

匹配某个具体文件
●(location =完整路径) > (location ^~完整路径) > (location ~完整
路径) > (location ~完整路径) > (location 完整路径) > (location /)
用目录做匹配访问某个文件
●(location=目录) > (location ^~目录/) > (location~目录) >
(location ~
目录) > (location 目录) > (location /)

二、根据不同应用场景下实现Nginx Rewrite的配置实例

首先我们先安装好域名解析named服务包——bind以及nginx服务(也可以使用手工编译,这里我们使用yum直接安装)

1.安装bind设置配置文件(三个)并开启服务

[root@localhost ~]# yum install bind -y
[root@localhost named]# netstat -napt | grep named
tcp        0      0 192.168.68.145:53       0.0.0.0:*               LISTEN      6077/named          
tcp        0      0 127.0.0.1:53            0.0.0.0:*               LISTEN      6077/named          
tcp        0      0 127.0.0.1:953           0.0.0.0:*               LISTEN      6077/named          
tcp6       0      0 ::1:53                  :::*                    LISTEN      6077/named          
tcp6       0      0 ::1:953                 :::*                    LISTEN      6077/named

2.安装nginx

我们会看到直接使用yum安装无法成功的

[root@localhost ~]# yum install -y nginx
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.cn99.com
 * extras: mirrors.cn99.com
 * updates: mirrors.cn99.com
没有可用软件包 nginx。
错误:无须任何处理
[root@localhost ~]# rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
获取http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
警告:/var/tmp/rpm-tmp.aXVptL: 头V4 RSA/SHA1 Signature, 密钥 ID 7bd9bf62: NOKEY
准备中...                          ################################# [100%]
正在升级/安装...
   1:nginx-release-centos-7-0.el7.ngx ################################# [100%]
[root@localhost ~]# yum install -y nginx
...省略部分内容

3.检查安装是否成功,查看配置文件目录

[root@localhost ~]# rpm -q nginx
nginx-1.16.1-1.el7.ngx.x86_64
[root@localhost ~]# rpm -qc nginx
/etc/logrotate.d/nginx
/etc/nginx/conf.d/default.conf   #这是我们待会做rewrite需要配置更改的文件
/etc/nginx/fastcgi_params
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/etc/nginx/win-utf
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug

2.1 rewrite规则配置应用场景一:基于域名的跳转

简单解释一下该场景:某公司出于某些原因需要将旧的域名修改为新的域名,但是新的域名大家都比较陌生,所以就需要进行旧——新的跳转,即:客户机上访问该旧的域名时可以自动跳转到新的域名,客户经过多次访问,发现只要输入新的域名就能访问了,而且输入更加简单友好。

下面我们结合上述的场景来具体阐述如何进行配置:

1.首先我们是yum安装的,上面已经注释了其主配置文件(是一个默认的配置文件,功能必然没有手工编译丰富):/etc/nginx/conf.d/default.conf,简要介绍一下其文件内容结构

[root@localhost named]# cd /etc/nginx/conf.d/
[root@localhost conf.d]# ls
default.conf
[root@localhost conf.d]# cat default.conf 
server {
    listen       80;                           #监听端口
    server_name  localhost;                    #域名,一般是指服务器的域名

    #charset koi8-r;                          #字符设置 
    #access_log  /var/log/nginx/host.access.log  main;      #访问日志路径设置

    location / {    #location 有”定位”的意思, 根据Uri来进行不同的定位,Uri可以理解为资源对应于URL是地址
        root   /usr/share/nginx/html;      
        index  index.html index.htm;
    }
    #location可以把网站的不同部分,定位到不同的处理方式上

    #error_page  404              /404.html;    #404访问错误页面找不到

    # redirect server error pages to the static page /50x.html           
    #
    error_page   500 502 503 504  /50x.html;              #错误页面,服务器出问题
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

2.更改配置操作:更改域名、域名重定向

 server {
    listen       80;                    
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        if ($host = 'www.lokott.com'){
                rewrite ^/(.*)$ http://www.newlokott.com/$1 permanent;
        }

3.开启nginx服务关闭防火墙

[root@localhost conf.d]# systemctl start nginx
[root@localhost conf.d]# systemctl stop firewalld.service 
[root@localhost conf.d]# setenforce 0

4.测试是否正常跳转

在win10上输入旧的域名:www.lokott.com是否正常跳转为www.newlokott.com

旧域名输入界面,按完回车后跳转为下面第二张界面,可以验证的确将旧域名跳转到新的域名了。

Nginx Rewrite的实现原理和使用方法

Nginx Rewrite的实现原理和使用方法

2.2  rewrite规则配置应用场景二:基于ip地址

简单描述:公司网页正在做维护或者结构调整,目前只允许合法的ip地址访问公司的页面,其他的就跳转到维护或者其他页面。

具体配置:

1.设置一个合法的标志位;set $rewrite true;

2.判断是否是合法的IP,是就正常跳转,否则跳转为main.html页面;

[root@localhost ~]# vim /etc/nginx/conf.d/default.conf 
[root@localhost ~]# cat /etc/nginx/conf.d/default.conf 
server {
    listen       80;
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    set $rewrite true;                      #由此开始配置场景二
    if ($remote_addr = "192.168.68.151"){
        set $rewrite false;
    }   

    if ($rewrite = true){
        rewrite (.+) /main.html;
    }

    location = /main.html {
        root /usr/share/nginx/html;
    }                                       #到此配置二结束

    location / {
        #if ($host = 'www.lokott.com'){     #注释场景一的配置
        #       rewrite ^/(.*)$ http://www.newlokott.com/$1 permanent;
        #}
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

3.将main.html页面写到/usr/share/nginx/html/下

[root@localhost ~]# cd /usr/share/nginx/html/
[root@localhost html]# ls
50x.html  index.html
[root@localhost html]# echo "this is a maintenance web page" > main.html
[root@localhost html]# ls
50x.html  index.html  main.html

4.重启nginx服务,然后之后检验

[root@localhost html]# systemctl restart nginx
[root@localhost html]# netstat -antp | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      64979/nginx: master 

5.根据上面的配置,结果应该是IP地址为192.168.68.151的主机是可以正常访问的,其他的则无法访问。

实际的结果如下:

Nginx Rewrite的实现原理和使用方法

换一台centos虚拟机测试则无法访问正常的页面

Nginx Rewrite的实现原理和使用方法

下面,我们对于刚刚配置文件的内容做逻辑层面上的梳理与对应解释:

截取关键部分的配置命令:

set $rewrite true;                      #设置一个标志位用来进行不同的判断从而触发不同的操作过程
if ($remote_addr = "192.168.68.151"){   #判断请求访问的主机ip地址是否是被允许的(只有该地址有权限进行正常访问)
set $rewrite false;                           #更改标志位的值,从而不触发原本为true的操作,即不执行下面两段的操作
}

if ($rewrite = true){                                 #若是非法地址访问则该标志位仍然为true,从而执行该段内容
rewrite (.+) /main.html;
}

location = /main.html {           #基于上面的true匹配在精确匹配进行具体操作执行的定位,访问的是维护页面
root /usr/share/nginx/html;
}

所以根据逻辑上的理解,我们知道只有被设置为允许的ip地址的客户机才能正常访问公司页面,则其他的没有改权限,相当于做了一个“白名单”。

2.3  rewrite规则配置应用场景三:基于跳转到新域名后面有目录的情况

场景简述:加入访问的是www.lokott.com/p,现在需要将这个域名下面的发帖都跳转到bbs.lokott.com/ss/p,

1.我们仍然对默认主配置文件进行修改

[root@localhost ~]# cat /etc/nginx/conf.d/default.conf 
server {
    listen       80;
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    set $rewrite true;
    if ($remote_addr = "192.168.68.151"){
        set $rewrite false;
    }   

    if ($rewrite = true){
        rewrite (.+) /main.html;
    }

    location = /main.html {
        root /usr/share/nginx/html;
    }

    location /p {                                      #第三个场景配置
        rewrite (.+) http://bbs.lokott.com/ss$1 permanent;    
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

2.重启服务

[root@localhost html]# systemctl restart nginx

3.在win10虚拟机上测试

Nginx Rewrite的实现原理和使用方法

Nginx Rewrite的实现原理和使用方法

由此现象可见,上述$1的含义是:你所定义的location的/p目录之后的内容,具体为何需要你自己创建站点,例如:

在/usr/local/nginx/html目录下创建ss/p/index.html网页,网页内容为“hello world” ,在使用http://www.lokott.com/p/index访问时将会如下图跳转:

Nginx Rewrite的实现原理和使用方法

2.4  rewrite规则配置应用场景四:基于多参数匹配

场景简述:在访问www.lokott.com域名时在后面输入已经规定的参数,实现规则跳转,例如:输入http://www.lokott.com/100-200-4454.html则跳到首页

1.更改配置文件

server {
    listen       80;
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    if ($request_uri ~ ^/100-(100|200)-(\d+).html$){     #第四个场景
        rewrite (.*) http://www.lokott.com permanent;      //
    }
    #上述涉及的正则:^——开头 | 或   \ 转义  d+ 数字匹配
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

2.重启服务

[root@localhost html]# systemctl restart nginx
[root@localhost html]# echo "asda" > 100-200-4454.html
[root@localhost html]# ls
100-200-4454.html  50x.html  index.html 
[root@localhost html]# echo "asda" > 100.html

3.测试验证

Nginx Rewrite的实现原理和使用方法

Nginx Rewrite的实现原理和使用方法

在站点目录在创建一个100.html文件,内容为asda,然后进行测试,结果如下:

Nginx Rewrite的实现原理和使用方法

2.5 rewrite规则配置应用场景五:基于文件后缀名访问

场景简述:访问upload目录下的php文件时跳转至主页面

1.修改配置文件

server {
    listen       80;
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location ~* /upload/.+\.php$ {                       #第五个场景
        rewrite (.+) http://www.lokott.com permanent;
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

2.重启服务

[root@localhost html]# systemctl restart nginx

3.测试验证

Nginx Rewrite的实现原理和使用方法

跳转的页面:

Nginx Rewrite的实现原理和使用方法

2.6 rewrite规则配置应用场景六:基于指定文件(具体页面)匹配

场景简述:访问固定的页面时跳转到首页

1.修改配置文件

server {
    listen       80;
    server_name  www.lokott.com;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location ~* ^/abc/123.html {                         #第六个场景
        rewrite (.+) http://www.lokott.com permanent;
    }
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

2.重启服务

[root@localhost html]# systemctl restart nginx

3.测试验证

Nginx Rewrite的实现原理和使用方法

跳转页面如下:

Nginx Rewrite的实现原理和使用方法

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI