How to I get variables from location in nginx?

50,367

Solution 1

The regex works pretty much like in every other place that has it.

location ~/photos/resize/(\d+)/(\d+) {
  # use $1 for the first \d+ and $2 for the second, and so on.
}

Looking at examples on the nginx wiki may also help, http://wiki.nginx.org/Configuration

Solution 2

In addition to the previous answers, you can also set the names of the regex captured groups so they would easier to be referred later;

location ~/photos/resize/(?<width>(\d+))/(?<height>(\d+)) {
  # so here you can use the $width and the $height variables
}

see NGINX: check whether $remote_user equals to the first part of the location for an example of usage.

Solution 3

You may try this:

location ~ ^/photos/resize/.+ {
    rewrite ^/photos/resize/(\d+)/(\d+) /my_resize_script.php?w=$1&h=$2 last;
}
Share:
50,367

Related videos on Youtube

Alex Z
Author by

Alex Z

I love calculators

Updated on September 18, 2022

Comments

  • Alex Z
    Alex Z over 1 year

    The location from nginx conf:

    location ~/photos/resize/(\d+)/(\d+) {
        # Here var1=(\d+), var2=(\d+)
    }
    

    How to I get variables from location in nginx?

  • KajMagnus
    KajMagnus about 6 years
    This is apparently necessary, if there's also another nested location with another regex and regex capture groups. Because inside that other location, $1 $2 $3 etc will refer to values from the nested regex, overwriting the $1 $2 ... in the outer regex. An alias /$1 in the outer regex, will use the $1 from the inner regex, which likely results in file-not-found.
  • Cameron Kerr
    Cameron Kerr about 6 years
    I think you can just write (?<width>\d+) instead of (?<width>(\d+)), or is there some other reason for this -- perhaps to also get $1 as well as $width ?