Rewriting $uri to include session id from cookie

In order to implement user dependended memcached lookup for URIs I would
like to rewrite the URI to include the value of the session_id cookie as
a query parameter but somehow I can’g get it working. I’ve tried these
variations:

location /
{

SNIP - Solution A - not working

if ($http_cookie !~ “session_id=?(.+)”)
{
rewrite ^?(.*) $2?session_id=$1;
}

SNIP - Solution A - not working

SNIP - Solution B - not working

if ($http_cookie !~ “session_id=?(.+)”)
{
set $tmp $1
rewrite ^?(.*) $1?session_id=$tmp;
}

SNIP - Solution B - not working

Check if local memcached server can answer this request

set $memcached_key $uri;
memcached_pass 127.0.0.1:11211;
error_page 404 = @cache_miss;
}

location @cache_miss
{
proxy_pass http://backend;
}

Could someone tell me what I’m doing wrong?