1

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?

1
  • 2
    That is called the path, and it is not the last part of a URL. A query string and fragment may follow it. Jun 11, 2015 at 17:36

2 Answers 2

8

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.

1
1

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.

1
  • 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 still location /whatever { return http://example.com$request_uri; }.
    – AD7six
    Jun 11, 2015 at 17:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .