0

I have a nginx.conf which basically looks like (unnecessary parts omitted):

upstream app {
    server unix:/tmp/unicorn.myapp.sock fail_timeout=0;
}

server {
    listen 80;

    location @app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app;
    }
}

I want to configure nginx so that the value of a specific header is used to rewrite the url being passed to the upstream.

For example, let's assume that I have a request to /test with the header Accept: application/vnd.demo.v1+json. I'd like it to be redirected to the upstream URL /v1/test, i.e. basically the upstream app will receive the request /v1/test without the header.

Similarly, the request to /test and the header Accept: application/vnd.demo.v2+json should be redirected to the upstream URL /v2/test.

Is this feasible? I've looked into the IfIsEvil nginx module, but the many warnings in there made me hesitant to use it.

Thanks,

r.

edit

In case there's no match, I'd like to return a 412 Precondition Failed immediately from nginx.

1 Answer 1

5

If Accept header does not contain required header return error.

map $http_accept $version {
    default "";
    "~application/vnd\.demo\.v2\+json" "v2";
    "~application/vnd\.demo\.v1\+json" "v1";
}

server {

    location @app {
        if ($version = "") {
            return 412;
        }
        ...;
        proxy_pass http://app/$version$uri$is_args$args;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your input. You're right I didn't specify it (I've edited the original question). Is there a way to directly return a 412 Precondition Failed in case the header does not contain any matching type?
You could set default to something else and use if to check variable value.
Thank you, even though I'm a little allergic to if statements after all the warnings that are on the official docs ^^_
> There are cases where you simply cannot avoid using an if, for example if you need to test a variable which has no equivalent directive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.