nginx的rewrite重写

Posted givenchy_yzl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nginx的rewrite重写相关的知识,希望对你有一定的参考价值。

一、rewrite基本概述

1.什么是rewrite?
Rewrite主要实现url地址重写,以及重定向,就是把传入web的请求重定向到其他url的过程。

2.rewrite的使用场景
1、地址跳转,用户访问www.drz.com这个URL是,将其定向至一个新的域名mobile.drz.com
2、协议跳转,用户通过http协议请求网站时,将其重新跳转至https协议方式
3、伪静态,将动态页面显示为静态页面方式的一种技术,便于搜索引擎的录入,同时建上动态URL地址对外暴露过多的参数,提升更高的安全性。
4、搜索引擎,SEO优化依赖于url路径,好记的url便于搜索引擎录入

3.rewrite语法

Syntax:	rewrite regex replacement [flag];
Default:	—
Context:	server, location, if

server {
	rewrite 规则 路径或者内容 flag类型;
	rewrite (.*) http://www.baidu.com$1
}
rewrite          #模块命令
regex            #请求的链接(支持正则表达式)
replacement      #跳转的链接
[flag];          #标签

1.规则:字符串,也可以使用正则匹配url;
2.路径或者内容:表示匹配到规则后要跳转的路径或内容,如果前面规则里面有正则,则可以使用$1等获取值
3.flag类型:last break redirect permanent

4.Rewrite标记Flag
rewrite指令根据表达式来重定向URL,或者修改字符串,可以应用于server,location,if环境下,每行rewrite指令最后跟一个flag标记,支持的flag标记有如下表格所示:
在这里插入图片描述

4.1)last与break的区别

[root@web01 conf.d]# cat rewrite.conf 
server {
        listen 80;
        server_name rewrite.drz.com;
        root /code;

        location ~ ^/break {
                rewrite ^/break /test/ break;
        }
        location ~ ^/last {
                rewrite ^/last /test/ last;
        }
        location /test/ {
                default_type application/json;
                return 200 "ok";
        }
}

#重启nginx服务
[root@web01 conf.d]# nginx -t 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 conf.d]# nginx -s reload

4.2)浏览器访问break
在这里插入图片描述
浏览器访问last
在这里插入图片描述
4.3)结论

break 只要匹配到规则,则会去本地配置路径的目录中寻找请求的文件;
而last只要匹配到规则,会对其所在的server(...)标签重新发起请求。

break请求:
1、请求rewrite.drz.com/break
2、首先:会去查找本地的/code/test/index.html;
3、如果找到了,则返回/code/test/index.html的内容;
4、如果没找到该目录则报错404,如果找到该目录没找到对应的文件则403

last请求:
1、请求rewrite.drz.com/last
2、首先:会去查找本地的/code/test/index.html;
3、如果找到了,则返回/code/test/index.html的内容;
4、如果没找到,会对当前server重新的发起一次请求,rewrite.drz.com/test/
5、如果有location匹配上,则直接返回该location的内容。
6、如果也没有location匹配,再返回404;

所以,在访问/break和/last请求时,虽然对应的请求目录/test都是不存在的,理论上都应该返回404,但是实际上请求/last的时候,是会有后面location所匹配到的结果返回的,原因在于此。

5.redirect和permanent的区别

[root@web01 conf.d]# cat rewrite.conf 
server {
        listen 80;
        server_name rw.linux.com;
        root /code/rewrite;
        location /test {
                rewrite ^(.*)$ http://www.mumusir.com redirect;
                #rewrite ^(.*)$ http://www.mumusir.com permanent;
        }
}

redirect: 每次请求都会询问服务器,如果当服务器不可用时,则会跳转失败。(临时重定向)
permanent: 第一次请求会询问,浏览器会记录跳转的地址,第二次则不再询问服务器,直接通过浏览器缓存的地址跳转。(永久重定向)

二、四、rewrite规则匹配实例

1.用户访问/abc/1.html实际上真实访问的是/ccc/bbb/2.html

[root@web01 conf.d]# vim rw.conf 
server {
    listen 80;
    server_name rw.linux.com;
    root /code;

    location ~ /abc {
        rewrite ^(.*)$ /ccc/bbb/2.html redirect;
        #rewrite /abc/1.html /ccc/bbb/2.html redirect;
    }
}

#/abc/1.html   /ccc/bbb/1.html
    location ~ /abc {
        rewrite /abc/(.*)\\.html /ccc/bbb/$1.html redirect;
    }

2.用户访问/2018/ccc/2.html实际上真实访问的是 /2014/ccc/bbb/2.html

[root@web01 conf.d]# mkdir /code/2014/ccc/bbb/ -p
[root@web01 conf.d]# echo "2014-ccc-bbb-222" > /code/2014/ccc/bbb/2.html
server {
    listen 80;
    server_name rw.linux.com;
    root /code;

    location ~ /2018 {
        rewrite /2018/ccc/2.html /2014/ccc/bbb/2.html redirect;
    }
}

#/2018/ccc/bbb/2.html  跳转 /2014/ccc/bbb/2.html
    location ~ /2018 {
        rewrite /2018/(.*) /2014/$1 redirect;
    }

3.用户访问/test实际上真实访问的是www.baidu.com

server {
    listen 80;
    server_name rw.linux.com;
    root /code;

    location ~ /test {
        rewrite (.*) https://www.baidu.com redirect;
    }
}

4.用户访问 couese-11-22-33.html 实际上真实访问的是

/course/11/22/33/course_33.html
[root@web01 conf.d]# mkdir /code/course/11/22/33/ -p
[root@web01 conf.d]# echo "course-111-222-333" > /code/course/11/22/33/course_33.html
[root@web01 conf.d]# vim rw.conf 
server {
    listen 80;
    server_name rw.linux.com;
    root /code;

    location / {
        #rewrite  ^/course-11-22-33.html  /course/11/22/33/course_33.html redirect;
        rewrite ^/(.*)-(.*)-(.*)-(.*).html /$1/$2/$3/$4/$1_$4.html redirect;
    }
}

5.将http请求跳转到https

server {
	listen 80;
	server_name www.mumusir.com;
	#rewrite (.*) https://www.mumusir.com redirect;
	return 302 https://www.mumusir.com;
}

http://www.mumusir.com  --> https://www.mumusir.com

server {
	listen 443;
	server_name www.mumusir.com;
	ssl on;
	ssl...... *.key;
	ssl..... *.crt;
}

三、rewrite案例

项目需求

部署discuz,并实现伪静态
实现https
实现实时备份

一、实验准备

1.在discuz官网上下载到discuz压缩包并上传到web01中的/www/discuz目录下并解压
2.backup机器已经配置完成
3.nfs挂载点创建完成

二、mysql

#登录数据库
[root@db01 ~]# mysql -uroot -p123
#创建数据库
MariaDB [(none)]> create database discuz;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]>  grant all on discuz.* to yzl@'%' identified by '123';
Query OK, 0 rows affected (0.08 sec)

三、web服务器

#编辑discuz网页配置文件
[root@web01 conf.d]# vim discuz.conf
server{
    listen 80;
    server_name linux.discuz.com;
    location / {
        root /www/discuz/upload;
        index index.php index.html;
    }
    include php.params;
}

#编辑PHP配置文件
[root@web01 conf.d]# vim php.params
location ~ \\.php$ {
    root /www/discuz/uplod;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

#创建站点目录部署代码
[root@web01 conf.d]# mkdir /www/discuz
[root@web01 conf.d]# cd /www/discuz/
[root@web01 discuz]# rz -E
rz waiting to receive.
[root@web01 discuz]# unzip Discuz_X3.4_SC_UTF8_20210320.zip 

#测试并重启
[root@web01 www]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 www]# systemctl restart nginx

#在本地hosts中添加
192.168.1.7   linux.discuz.com

#在浏览器访问、并安装

#随便发表一篇帖子,获取到帖子的url地址如下:
http://linux.discuz.com/forum.php?mod=viewthread&tid=1&extra=

#为网站设置伪静态
[root@web01 www]# vim /etc/nginx/conf.d/discuz.conf 
server {
    listen 80;
    server_name linux.discuz.com;

    location / {
        root /www/discuz/upload;
        index index.php;
        rewrite ^([^\\.]*)/topic-(.+)\\.html$ $1/portal.php?mod=topic&topic=$2 last;
        rewrite ^([^\\.]*)/article-([0-9]+)-([0-9]+)\\.html$ $1/portal.php?mod=view&aid=$2&page=$3 last;
        rewrite ^([^\\.]*)/forum-(\\w+)-([0-9]+)\\.html$ $1/forum.php?mod=forumdisplay&fid=$2&page=$3 last;
        rewrite ^([^\\.]*)/thread-([0-9]+)-([0-9]+)-([0-9]+)\\.html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3D$4&page=$3 last;
        rewrite ^([^\\.]*)/group-([0-9]+)-([0-9]+)\\.html$ $1/forum.php?mod=group&fid=$2&page=$3 last;
        rewrite ^([^\\.]*)/space-(username|uid)-(.+)\\.html$ $1/home.php?mod=space&$2=$3 last;
        rewrite ^([^\\.]*)/blog-([0-9]+)-([0-9]+)\\.html$ $1/home.php?mod=space&uid=$2&do=blog&id=$3 last;
        rewrite ^([^\\.]*)/(fid|tid)-([0-9]+)\\.html$ $1/archiver/index.php?action=$2&value=$3 last;
        rewrite ^([^\\.]*)/([a-z]+[a-z0-9_]*)-([a-z0-9_\\-]+)\\.html$ $1/plugin.php?id=$2:$3 last;
        if (!-e $request_filename) {
            return 404;
        }

    }
    include php.params;
}

[root@web01 conf.d]# systemctl restart nginx

#对比网址
伪静态前帖子网址:http://linux.discuz.com/forum.php?mod=viewthread&tid=1&extra=
伪静态后帖子网址http://linux.discuz.com/thread-1-1-1.html

#实现https


#检查nginx能否使用证书
[root@web01 ~]# nginx -V
--with-http_ssl_module
#必须有上面这个模块才可以使用证书

#创建证书存放目录
[root@web01 ~]# mkdir /etc/nginx/ssl_key
[root@web01 ~]# cd /etc/nginx/ssl_key/

#生成证书
[root@web01 ssl_key]#  openssl genrsa -idea -out server.key 2048
Generating RSA private key, 2048 bit long modulus
.......................................................................+++
.+++
e is 65537 (0x10001)
Enter pass phrase for server.key:123456  # 密码4-1023位即可
Verifying - Enter pass phrase for server.key:123456  #确认密码

[root@web01 ssl_key]# openssl req -days 36500 -x509 -sha256 -nodes -newk
ey rsa:2048 -keyout server.key -out server.crt
Generating a 2048 bit RSA private key
........................................................+++
...........................................+++
writing new private key to 'server.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:zg
State or Province Name (full name) []:riben
Locality Name (eg, city) [Default City]:pari
Organization Name (eg, company) [Default Company Ltd]:oldboy
Organizational Unit Name (eg, section) []:oldboy
Common Name (eg, your name or your server's hostname) []:discuz
Email Address []:123@qq.com

#命令注解
openssl req -days 36500 -x509 -sha256 -nodes -newkey rsa:2048 -keyout server.key -out server.crt
# req  --> 用于创建新的证书
# new  --> 表示创建的是新证书    
# x509 --> 表示定义证书的格式为标准格式
# key  --> 表示调用的私钥文件信息
# out  --> 表示输出证书文件信息
# days --> 表示证书的有效期

[root@web01 ssl_key]# ll
total 8
-rw-r--r-- 1 root root 1375 May  8 11:12 server.crt
-rw-r--r-- 1 root root 1704 May  8 11:12 server.key

#配置nginx证书
[root@web01 ssl_key]# vim /etc/nginx/conf.d/discuz.conf
server {
    listen 443 ssl;
    server_name linux.discuz.com;
    ssl_certificate /etc/nginx/ssl_key/server.crt;
    ssl_certificate_key /etc/nginx/ssl_key/server.key;
    #rewrite ^(.*)$ https://$server_name$1;
    location / {
        root /www/discuz/upload;
        index index.php;
        rewrite ^([^\\.]*)/topic-(.+)\\.html$ $1/portal.php?mod=topic&topic=$2 last;
        rewrite ^([^\\.]*)/article-([0-9]+)-([0-9]+)\\.html$ $1/portal.php?mod=view&aid=$2&page=$3 last;
        rewrite ^([^\\.]*)/forum-(\\w+)-([0-9]+)\\.html$ $1/forum.php?mod=forumdisplay&fid=$2&page=$3 last;
        rewrite ^([^\\.]*)/thread-([0-9]+)-([0-9]+)-([0-9]+)\\.html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3D$4&page=$3 last;
        rewrite ^([^\\.]*)/group-([0-9]+)-([0-9]+)\\.html$ $1/forum.php?mod=group&fid=$2&page=$3 last;
        rewrite ^([^\\.]*)/space-(username|uid)-(.+)\\.html$ $1/home.php?mod=space&$2=$3 last;
        rewrite ^([^\\.]*)/blog-([0-9]+)-([0-9]+)\\.html$ $1/home.php?mod=space&uid=$2&do=blog&id=$3 last;
        rewrite ^([^\\.]*)/(fid|tid)-([0-9]+)\\.html$ $1/archiver/index.php?action=$2&value=$3 last;
        rewrite ^([^\\.]*)/([a-z]+[a-z0-9_]*)-([a-z0-9_\\-]+)\\.html$ $1/plugin.php?id=$2:$3 last;
        if (!-e $request_filename) {
            return 404;
        }

    }
    include php.params;
}

#重启nginx
[root@web01 ssl_key]# systemctl restart nginx

#浏览器输入:https://linux.discuz.com
#注:此时已完成https访问,但没有完成输入HTTP跳转到https

#在nfs+backup准备好后挂载即可

四、backup+nfs

backup
#开启rsyncd服务
[root@web01 ~]#systemctl restart rsyncd



nfs上
[root@nfs ~]# systemctl restart nfs
[root@nfs ~]# cd /usr/local/sersync2/
#更改conf.xml文件#开启实时同步服务
[root@pingnfs sersync2]# ./sersync2 -dro ./confxml.xml

四、rewrite规则补充

1.rewrite匹配的优先级

1.先执行server模块的rewrite指令
2.其次执行location匹配规则
3.最后执行location里面的rewrite

server {
    listen 80;
    server_name rw.linux.com;
	#rewrite ^(.*)$ http://www.jingdong.com;

    location /test {
    	rewrite ^(.*)$ http://www.mumusir.com;
    }
    
    location =/ {
        rewrite ^(.*)$ http://www.baidu.com;
    }
}

2.rewrite全局变量

$server_name		#当前用户请求的域名
server {
    listen 80;
    server_name rw.linux.com;
    root /code;
	rewrite ^(.*)$ https://$server_name;
}

$request_filename	#请求的文件路径和名字(带着网站站点目录的路径和文件 /code/images/1.jpg)
$request_uri		#请求的文件路径和名字(不带网站站点目录的路径和文件 /images/1.jpg)

server {
    listen 80;
    server_name rw.linux.com;
    root /code;
	rewrite ^(.*)$ https://$server_name$request_uri;
}


#很久很久以前,网站优化
server {
    listen 80;
    server_name www.baidu.com baidu.com;
    root /code;
	if ($http_host = baidu.com) {
		rewrite (.*) http://www.baidu.com;
	}
}

#实际写法
server {
    listen 80;
    server_name baidu.com;
    rewrite (.*) http://www.baidu.com;

}
server {
    listen 80;
    server_name www.baidu.com;
    root /code;
}

3.rewrite可以开启日志

#NGINX主配置文件,错误日志级别改成notice
error_log  /var/log/nginx/error.log notice;

#http层开启rewrite日志
rewrite_log on;

以上是关于nginx的rewrite重写的主要内容,如果未能解决你的问题,请参考以下文章

第十八章 Nginx Rewrite重写

Nginx Rewrite重写

Nginx Rewrite重写

Nginx URL重写(rewrite)配置及信息详解

Nginx URL重写(rewrite)配置及信息详解

nginx rewrite url重写, if,负载均衡 ,nginx反向代理配置