7

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?

1 Answer 1

5

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
    }
}
3
  • upstream directive was what I was looking for. Thanks. Commented Jan 26, 2012 at 7:30
  • Though I am commenting to an age old reply, but may be useful for anyone who reads it in future. The common proxy header directives are masked if you add another header in a location directive for some special processing. Commented May 31, 2021 at 15:02
  • blog.martinfjordvald.com/… explains that
    – kolbyjack
    Commented Jun 1, 2021 at 16:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .