nginx地址重写

2020-03-03  本文已影响0人  磨剑_运维之旅

rewrite就是重定向, 就是将接收到的请求依据配置规则重定向称为另一个请求返回; 实际使用中非常方便,比如消息转发, 错误页面的处理等; nginx的ngx_http_rewrite_module模块实现了对URL的判断,正则,重定向;

基本指令:

# 根据nginx提供的变量或模块提供的变量来判断,产生对应动作;
server {
    listen      80;
    server_name www.cc.com;

    access_log  logs/cccom/access_log   main;
    error_log   logs/cccom/error.log;

    location / {
        if ($http_user_agent != MSIE) {
            return 403;
        }
        root    html/cccom;
        index   index.html;
    }
}
An optional flag parameter can be one of:

-last
stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;
-break
stops processing the current set of ngx_http_rewrite_module directives as with the break directive;
-redirect
returns a temporary redirect with the 302 code; used if a replacement string does not start with “http://”, “https://”, or “$scheme”;
-permanent
returns a permanent redirect with the 301 code.

演示:

# 检测rewrite和return的执行顺序;
server{
    listen      80;
    server_name www.cc.com;

    access_log  logs/cccom/access_log   main;
    error_log   logs/cccom/error.log;

    location / {
        if ($http_user_agent != MSIE) {
            return 403;
        }
        root    html/cccom;
        index   index.html;
    }

    location /one {
        rewrite /one/(.*) /two/$1;
        #return 200 'hello one';
    }

    location /two {
        rewrite /two/(.*) http://www.cloud1908.com/three/$1 permanent;
        #return 200 'hello two';
    }

    location /three {
        return 200 "hello third";
    }
}

实例: 防止SQL注入的rewrite使用功能

# 通过判断URI中是否有 ’ ; > < 等字符可以快速过滤掉可能发生SQL注入的请求,然后直接返回"404 Not Found"
# http://www.c.com/login.php?param01=`create`&param02=`database`&param=`dq;` -> query_string

if ( $uri ~* ".*[;`<>].*" ) {
    return 404;
}

实例: 当用户访问的资源不存在时,直接重定向至自定义页面

location / {
    root   html;
    index  index.html index.htm;
    if (!-e $request_filename) {
      rewrite ^(.*)$ /notfound.html break;
    }
}
location / {
    root   html;
    index  index.html index.htm;
    if (!-e $request_filename) {
      rewrite ^(.*)$ /notfound.html break;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读