nginx rewrite

(1)rewrite基本介绍

1.rewrite作用
主要实现url重写以及重定向,实现伪静态
2.rewrite语法:

	syntax: rewrite regex replacement [flag]
	context: server,location,if 
例:rewrite ^/(.*) http://www.abc.com/$1 permanent;
rewrite 			//为固定关键字,表示开始进行rewrite匹配规则
regex ^/(.*) 		//正则表达式,匹配完整的域名和后面的路径
replacement			// http://www.abc.com/$1 $1取regex中的()里的内容,匹配成功后跳转URL 
flag		
	last			//停止rewrite检测
	break			//停止rewrite检测
	redirect		//返回302临时重定向,每一次都请求
	permanent		//返回301永久重定向,使用本地缓存

3.正则表达式:省略
4.正则表达式字段测试工具

#yum install pcre-tools -y 
#pcretest

(2)rewrite案例

1.访问www.test.com跳转到www.baidu.com

    server {
        listen       80;
        server_name www.test.com;
		if ($host = "www.test.com"){
        rewrite .*  http://www.baidu.com  break;
        }

2.访问test.com跳转到www.test.com 301跳转

    server {
        listen       80;
        server_name test.com;
		rewrite ^/(.*) www.test.com/$1 permanent;
        }
    server {
        listen       80;
        server_name test.com;
		if ( $host != "www.test.com" ) {
			rewrite ^/(.*) www.test.com/$1 permanent;
			}
		}

3.url重写:www.test.com/nginx/123.html 重写成www.123.com/123.html

    server {
        listen       80;
        server_name  www.test.com;
		rewrite "^.+nginx(.*)$" http://www.123.com$1 permanent;
		}
posted @ 2018-05-20 22:42  你很棒  阅读(361)  评论(0编辑  收藏  举报