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
    That is called the path, and it is not the last part of a URL. A query string and fragment may follow it. – Michael Hampton Jun 11 '15 at 17:36

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.

| improve this answer | |

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.

| improve this answer | |
  • 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 '15 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.