nginx之Rewrite

server {
    listen 80;

    default_type text/plain;
    server_name pcre.haosheng.vip;
    root html;
    index index.html;
    location / {
        echo "pcre.haosheng.vip";
        return 301 http://haosheng.cn;
    }

    # rewrite break
    location ~ /break/ {
        # rewrite break - url重写后,直接使用当前资源,不再执行location里余下的语句,完成本次请求,地址栏url不变
        rewrite /break/(\d+)$ /test?t=$1 break;
        rewrite /break/(\w+)$ /test?t=$1 break;
        echo "name = $request_uri";
        echo "name = $uri?$args";
    }

    # rewrite last
    location ~ /last/ {
        # url重写后,马上发起一个新的请求,再次进入server块,重试location匹配,超过10次匹配不到报500错误,地址栏url不变
        # last标识 会终止当前location其他阶段的执行 用rewrite后的uri去匹配location
        # 最终访问到 location /test {}
        rewrite /last/(\d+)$ /test?t=$1 last;
        rewrite /last/(\w+)$ /test?t=$1 last;
        echo "name = $request_uri";
        echo "name = $uri?$args";
    }

    location /test {
        echo "test = $request_uri";
        echo "test = $uri?$args";
    }

    # rewrite redirect
    location /redirect {
        # 返回302临时重定向,地址栏显示重定向后的url,爬虫不会更新url(因为是临时)
        rewrite /redirect /test redirect;
    }

    # rewrite permanent
    location /permanent {
        # 返回301永久重定向, 地址栏显示重定向后的url,爬虫更新url
        rewrite /permanent /test permanent;
    }
}

 

posted @ 2021-03-17 16:53  豆腐居士  阅读(53)  评论(0编辑  收藏  举报