Best way to get the $request_uri without the starting slash

I want to pass the $request_uri to memcached as the key but without the
starting slash, as our memcached key names are a prefixed integer which
can be referenced from the URI, as follows:

http://example.com/1000 -> prefix:1000

In nginx, the only (or all) variables that refer to the URI also contain
the starting slash. So if I were to use prefix:$request_uri as above I
would get prefix:/1000 as the key.

At the moment I’m solving this by using a regex conditional to set a key
name (this is paraphrased):

if ($request_uri ~* ^/(.*)$) {
set $request_key $1;
}

set $memcached_key prefix:$request_key;

So now I have the correct key name for memcached. Are there any better
ways of doing this? Would this have a serious impact on performance,
performing this conditional every time? Is it possible do this using set
without the conditional part?

Thanks for any help,
Matt.

On Monday 19 December 2011 13:54:33 Matthew Ward wrote:
[…]

So now I have the correct key name for memcached. Are there any better ways
of doing this? Would this have a serious impact on performance, performing
this conditional every time? Is it possible do this using set without the
conditional part?

You can utilize “map” module functionality for such tasks, e. g.:

map $request_uri $request_key {
default index;
~^/(.+)$ $1;
}

wbr, Valentin V. Bartenev

Thanks, that’s exactly what I was looking for.

The $1 didn’t work however, nginx complained about it being an
unreferenced variable, so I modified it to look like the examples in the
documentation (maybe you can’t reference pattern matches numerically
like elsewhere in the config?):

map $request_uri $request_key {
default index;
~^/(?P.+)$ $key;
}

Posted at Nginx Forum:
http://forum.nginx.org/read.php?2,220245,220299#msg-220299

On Tue, Dec 20, 2011 at 04:36:49AM -0500, WheresWardy wrote:

}
Yes, numeric references are not supported in map.

You can also change default to empty string:

map $request_uri $request_key {
default “”;
~^/(?P.+)$ $key;
}


Igor S.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs