P
P
prokoptsev2014-08-11 13:44:44
Django
prokoptsev, 2014-08-11 13:44:44

How to set up Nginx for internal content redirection?

Good day.
There are 2 django projects. Both projects are api for mobile application. The first project is the first version of the api, the second is the second. The second version is under development.
To test some functionality, stubs are prepared in the form of json files.
It is necessary to implement the following request scheme:
When accessing the url of the second version of api, you need to check whether this functionality is ready. If it responds with 404, then check if there is something in the stubs, if not there, then try to request the first version of the api. If the first version also returns 404, then only then return an error to the client.
I roughly imagine it like this:

upstream api_v1 {
  server unix:///tmp/api_v1_gunicorn.sock fail_timeout=0;
}

upstream api_v2 {
  server unix:///tmp/api_v2_gunicorn.sock fail_timeout=0;
}

server {
  listen 80;

#### API V2
  location /api/v2/ {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://api_v2;
    error_page 404 = @mock_api_v2;
  }

#### MOCK API V2
  location @mock_api_v2 {

    index index.json;
    root /path/to/dir/with/mock/files/;
    error_page 404 = @backend;
  }

#### REWRITE TO V1
  location @backend {
    rewrite           /api/v2/(.+)      /api/v1/$1 break;

    proxy_set_header  Host              $host;
    proxy_set_header  X-Real-IP         $remote_addr;
    proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;

    proxy_pass        http://api_v2;
    proxy_redirect    off;
  }

#### API V1
  location / {
    include proxy_params;
    proxy_pass http://api_v2;
  }
}

But for some reason, nothing comes of it.
When I make such a request:
GET /api/v2/old_method/
Instead of giving me what is at the address /api/v1/old_method/, 404 is immediately returned.
If someone knows how this happens, or what I'm doing wrong, or how to do it differently, please advise.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Micher, 2014-08-11
@Micher

location @api_v1 {
  include proxy_params;
  proxy_pass http://api_v1;
}

location @api_v2 {
  include proxy_params;
  proxy_pass http://api_v2;
}

location @mock_api_v2 {
  index index.json;
  root /path/to/dir/with/mock/files/;
}

location /api/v2/ {
  try_files @api_v2 @mock_api_v2 @api_v1;
}

L
Lynn "Coffee Man", 2014-08-11
@Lynn

#### API V2
  location /api/v2/ {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://api_v2;
    proxy_intercept_errors on; # <=====================
    error_page 404 = @mock_api_v2;
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question