Regex in rewrite

Hi everyone:
I recently got a problem about rewrite module.I want to rewrite request
like this:

first requst is /cache/XXX
/cache/XXX/ —> /XXX/
and set /XXX/ as memcache_key

if memcache cannot find the key
404 = /backend
/backend/ ----> /backend/?url=XXX

I write like this in nginx.conf:

rewrite ^/cache/?(.*)$ /$1;
set $memcached_key $1;
error_page 404 = /backend;

location = /backend {
rewrite ^/backend /?(.*)$ /backend/?url=$request_uri;

I cannot figure it out anyway
Thank you very much