有的时候我们访问后台网站时,会携带大量的参数,比如/test?id=1,像这种ur就会携带一些参数,由于有些参数名会携带一些敏感信息,我们希望在url中隐藏传递的参数,比如将/test?id=1改写为test1.html,这就叫URL Rewrite

如图,可以通过URL Rwrite将http://192.168.66.129/1.html改写为http://192.168.66.1:88/test?id=1
基本配置指令如下:
rewrite 改写前URL正则 改写后URL 标记
比如:
rewrite ^/([0-9]+).html$ /test?id=$1 break;
其中各个字段含义如下:
rewrite:改写指令
^/([0-9]+).html$:改写前URL正则,这里表示匹配以数字开头的html文件(实际场景会更复杂)
/test?id=$1:改写后的URL,$1表示改写前匹配到第一个正则的参数,比如1.html,此时$1就为1
break:表示标记。标记共有四种(last, break, redirect, permanent)
在应用服务器192.168.66.1起一个服务,监听88端口和路径/test,并返回接收到的参数,详细代码如下:
- const http = require('http');
- const url = require('url');
-
- const server = http.createServer((req, res) => {
- const parsedUrl = url.parse(req.url, true);
-
- if(parsedUrl.pathname === '/test') {
- const params = parsedUrl.query;
- res.writeHead(200, {'Content-Type': 'text/plain'});
- res.end(`Received parameters: ${JSON.stringify(params)}`);
- } else {
- res.writeHead(404, {'Content-Type': 'text/plain'});
- res.end('Not Found');
- }
- });
-
- server.listen(88, () => {
- console.log('Server is running at http://localhost:88/');
- });
之后,在nginx.conf中配置好rewrite规则

配置好后,访问192.168.66.129/1.html, 得到如下结果

这里只要是数字都行,比如换成156.html

不能是字符,字符匹配不上正则
