Search code examples
nginxnginx-reverse-proxynginx-config

Creating an nginx redirect while removing two subdirectories from the path


I have the following nginx redirect which needs to redirect all requests to a different domain name. It works fine.

However the request url will be like: https://example.com/abc/123/TOKEN

How can I reformat this in the redirect to be like: https://example.com/TOKEN

events {}
http {
server {
    listen       80  default_server;
    server_name  _;
    return 301 https://example.com/$request_uri;
}
}

Solution

  • The Nginx rewrite...permanent; statement can change the URL before generating a 301 redirect.

    For example:

    server {
        listen 80 default_server;
        rewrite ^/[^/]+/[^/]+(/.*)$ https://example.com$1 permanent;
    }
    

    Note: server_name _; is no longer necessary.