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?

Umut Benzer
  • 173
  • 1
  • 6

1 Answers1

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
    }
}
kolbyjack
  • 8,039
  • 2
  • 36
  • 29
  • `upstream` directive was what I was looking for. Thanks. – Umut Benzer Jan 26 '12 at 07: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. – John_Avi_09 May 31 '21 at 15:02
  • https://blog.martinfjordvald.com/understanding-the-nginx-configuration-inheritance-model/ explains that – kolbyjack Jun 01 '21 at 16:22