nginx redirects-map

最後更新: 2019-09-23

 


redirect by $request_uri

 

[1]

snippets/redirects-map.conf

map $request_uri    $redirect_uri  {
    default         "404";
    /r/a            "1";
    /r/b/c          "22";
}

[2]

######## redirect by map ########
include /etc/nginx/snippets/redirects-map.conf;

server {
    ...
    ######## redirect by map ########
    location = /404 { add_header Content-Type text/html; echo "404"; }
    location ~ ^/r/([0-9a-zA-Z]+) {
            if ( $request_uri ) { return 302 $redirect_uri; }
    }

}

# Test

curl -I http://datahunter.org/a

P.S.

更新 redirects-map.conf 後需要 'nginx -s reload'

 


redirect by $query_string

 

Link

http://MyDomain/?a=1

http://MyDomain/?a=3&b=1

snippets/redirects-map.conf

map $query_string $new_url {
    ~a=1                 http://datahunter.org/1;
    ~a=2                 http://datahunter.org/2;
    ~a=3&b=1|b=1&a=3     http://datahunter.org/31;   # 因為 query 是沒有分先後 
}

/etc/nginx/nginx.conf

######## redirect by map ########
include /etc/nginx/snippets/redirects-map.conf;

server {
    location = / { return 301 https://www.datahunter.org; }
    ...
    # 301 Moved Permanently
    if ( $new_url ) {
        return 301 $new_url;
    }
    ...
    location / {
        # if not "/" and not a matching redirect, try static assets, else 404
        try_files $uri $uri.html = 404;
        ...
    }
}

 

Creative Commons license icon Creative Commons license icon