千家信息网

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

发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,一、理论讲解1.1Nginx Rewrite简介Nginx Rwrite即Nginx服务的规则重写,主要的功能是实现浏览器访问HTTP URL的跳转,其中相关的正则表达式是基于Perl语言。一般来说,
千家信息网最后更新 2026年11月03日Nginx Rewrite的实现原理和使用方法

一、理论讲解

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 [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 namedtcp        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, langpacksLoading 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 nginxnginx-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]# lsdefault.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

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

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]# ls50x.html  index.html[root@localhost html]# echo "this is a maintenance web page" > main.html[root@localhost html]# ls50x.html  index.html  main.html

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

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

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

实际的结果如下:

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

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

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

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虚拟机上测试

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

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

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]# ls100-200-4454.html  50x.html  index.html [root@localhost html]# echo "asda" > 100.html

3.测试验证

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

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.测试验证

跳转的页面:

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.测试验证

跳转页面如下:

配置 场景 域名 服务 文件 页面 正则 目录 规则 内容 地址 语言 应用 不同 字符 服务器 路径 表达式 测试 功能 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 华服互联网科技怎么样 互联网核心科技是什么 中资互联网科技 互联网络科技有限公司 碳银互联网科技 银优互联网科技有限公司 互联网科技ppt模板 互联网金融和金融科技 互联网科技公司的市场部门 云创客互联网科技公司 须眉科技是互联网公司吗 来此购互联网科技有限公司 语蝶互联网科技有限公司 群盈汇互联网科技有限公司 山东星卡互联网科技有限公司官网 江苏苏星互联网科技有限公司 中天科技中国工业互联网 广州百诚互联网科技有限公司官网 易租星互联网科技有限公司 恒生科技互联网指数十大成分股 互联网科技官网 致骋互联网科技 汉立互联网科技有限公司联系电话 智腾互联网科技有限公司 允成互联网科技有限公司融资 佛山市拉法互联网科技有限公司 科技大学互联网 中和天地互联网科技有限公司 互联网安防科技感 神州科技互联网有限公司
0