Dnyaneshwar Kshirsagar
Dnyaneshwar Kshirsagar

Reputation: 121

convert url get parameters to url segment in nginx

I have this URL https://example.com/user?param1=value1&param2=value2&param3=value3

and have it to go to https://example.com/user/value1/value2/value3 on the Nginx server.

Just FYI it is WordPress site and I have added the following rule in the Nginx config file.

location ~ /user/ {
    if ($args ~* "^param1=(\d+)&param3=(\d+)&param3=(\d+)") {
    set $param1 $1;
    set $param2 $1;
    set $param3 $1;
    set $args '';
    rewrite ^.*$ /user/$param1/$param2/$param3 permanent;
    }
}

Upvotes: 1

Views: 555

Answers (1)

Richard Smith
Richard Smith

Reputation: 49722

Your solution has two errors, 1) the location does not match /user, and 2) the rewrite is also appending the original arguments.

This could be fixed by using an exact match location and a trailing ? on the rewrite. For example:

location = /user {
    ...
    rewrite ^ /user/$param1/$param2/$param3? permanent;
}

However, the map statement is a cleaner and extensible solution, for example:

map $request_uri $redirect {
    default                                                          0;
    ~*^/user?param1=(?<p1>\d+)&param2=(?<p2>\d+)&param3=(?<p3>\d+)$  /user/$p1/$p2/$p3;
}

server {
    ...
    if ($redirect) { return 301 $redirect; }
    ...
}

See this document for details.

Upvotes: 1

Related Questions