Nginx, redirecting a location block to another

For uri's starting with /c/ , I want to do a memcached key test, and return the key's value if exists. If there is no key, it should pass it to proxy.

I do it with this directive:

location ^~ /c/ {
    set $memcached_key "prefix:$request_uri";
    memcached_pass 127.0.0.1:11211;

    default_type       application/json;
    error_page 404 405 502 = @proxy
}

For all other requests, I want them to pass to the same proxy. I do it with the directive bellow:

location / {
    proxy_pass       http://127.0.0.1:5555;
    proxy_redirect   off; 
    proxy_set_header Host $host; 
    proxy_set_header X-Real_IP $remote_addr; 
    proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for;
}

And my @proxy location is this:

location @proxy {
    proxy_pass       http://127.0.0.1:5555;
    proxy_redirect   off; 
    proxy_set_header Host $host; 
    proxy_set_header X-Real_IP $remote_addr; 
    proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for;
}

As seen, @proxy is same with / . I don't want to copy paste my proxy configuration. Instead I want to redirect location / to @proxy. How can I redirect one location block to another? How can I get rid of duplicate configuration of proxy?


Solution 1:

The easiest thing to do would be to put all the common proxy settings into the server, then you'll just have a proxy_pass in each location. You can also use an upstream to avoid having the address:port in multiple places:

upstream _backend {
    server 127.0.0.1:5555;
}

server {
    proxy_redirect   off; 
    proxy_set_header Host $host; 
    proxy_set_header X-Real_IP $remote_addr; 
    proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for;

    location / {
        proxy_pass       http://_backend;
    }

    location @proxy {
        proxy_pass       http://_backend;
    }

    location ^~ /c/ {
        set $memcached_key "prefix:$request_uri";
        memcached_pass 127.0.0.1:11211;

        default_type       application/json;
        error_page 404 405 502 = @proxy
    }
}