In my config file, I need to extract the last part of a url into a variable for use in a redirect e.g. if the url is http://www.example.com/question, I need "question" so that I can set up a rewrite. How can I do this please?
2 Answers
This can be achieved as follows:
if ($request_uri ~* "([^/]*$)" ) {
set $last_path_component $1;
}
You can then use the $last_path_component var anywhere you wish. Note this regex will return everything after the last / which could include in url arguments, so if you do not need them, you will have to modify the regex above accordingly.
-
3
Use regular expression submatches --
rewrite ^(.*) http://host.example.com$1 permanent;
With regular expressions, the parentheses are metacharacters that groups text into capture blocks. The first parenthesis will be grouped into $1, the second into $2, and so on.
-
For the example in the answer it would be more appropriate to use
$request_uri
i.e.:rewrite ^ http://example.com$request_uri permanent;
or better stilllocation /whatever { return http://example.com$request_uri; }
.– AD7sixJun 11, 2015 at 17:18