nginx rewrite

前言

  • nginx version: nginx/1.18.0
  • CentOS Linux release 7.6.1810 (Core)

rewrite 语法

rewrite 的官方说明: http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

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

If the specified regular expression matches a request URI, URI is changed as specified in the replacement string. The rewrite directives are executed sequentially in order of their appearance in the configuration file. It is possible to terminate further processing of the directives using flags. If a replacement string starts with “http://”, “https://”, or “$scheme”, the processing stops and the redirect is returned to a client.

flag说明:

  • last: 本条规则匹配完成后,使用 replacement 重新匹配 location。replacement 部分应为有效的 location。浏览器上的地址不改变。
  • break: 本条规则匹配完成后,终止。返回root+replacement 指向的内容。replacement 部分应为相对于root的文件路径。浏览器上的地址不改变。
  • redirect: 返回302临时重定向到 replacement 部分给出的地址。 replacement 部分应为URL。浏览器上的地址改变。
  • permanent: 返回301永久重定向到 replacement 部分给出的地址。replacement 部分应为URL。浏览器上的地址改变。
	location /re-last/ {
		rewrite /re-last/(.*) /out/$1 last;
	}
	location /last/ {
		rewrite /last/(.*) /re-last/$1 last;
	}
	
	location /break {
		root   /usr/share/nginx/html;
		default_type text/html ;
		rewrite /break/(.*) /break/$1 break;
	}
	
	location /redirect {
		rewrite /redirect/(.*) /out/$1 redirect;
	}
	
	location /permanent {
		rewrite /permanent/(.*) /out/$1 permanent;
	}
	location ~* /out/(.*) {
		default_type text/html ;
		return 200 "hello, $1";
	}
  • 当请求为“/last/jack”时,/last/jack->/re-last/jack->/out/jack。访问效果如下图:
    在这里插入图片描述

  • 当请求为“/break/jack”时,返回/usr/share/nginx/html/break/jack文件。访问效果如下图:
    在这里插入图片描述

  • 当请求为“/redirect/jack”时,访问效果如下图:
    在这里插入图片描述

  • 当请求为“/permanent/jack”时,访问效果如下图:
    在这里插入图片描述

示例1:在请求路径前追加

	location /acticle/ {
		rewrite ^/(.*)$ /wode/$1;
	}
  • 将uri /article/xxx 前面追加 /wode。 /article/xxx 替换成 /wode/article/xxx。

示例2:替换路径

	location /article/ {
		rewrite ^/article/(.*)$ /wenzhang/$1;
	}
  • 将uri /article/xxx 替换成 /wenzhang/xxx。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值