A
A
Alexey2020-03-18 10:42:14
Nginx
Alexey, 2020-03-18 10:42:14

Is it possible to set up proxying in nginx by parsing the header method: GET, POST...?

The task is to proxy requests to nginx, balancing based on the header.
For example, the REST API has resources that only serve content. Their requests are made using the GET method. Such requests can be sent to mirrors that are read only.
And there are some resources that write to the database. They accept requests using POST, PUT, DELETE methods. They need to be redirected to the master server, where there is a record in the database.
And there is an ambush: some resources process all methods at once. Those. the heading determines whether to read or write.
Can nginx resolve such balancing? What are the options?
I know about HAProxy, this is an extreme option: I don’t want to drag an extra animal to the zoo.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2020-03-18
@alenov

There seems to be something on the subject.
There is a $request_method variable that can be used for balancing. I'm trying this configuration:

upstream master {
    server unix:/tmp/flask.sock;
}

upstream read_api {
    server api.service.ru;
}

map $request_method $upstream_location {
    GET         read_api;
    default     master;
}

server {
    listen 80;
    server_name service.ru;

    root /home/web/service;
    include uwsgi_params;
    include proxy_params;

    location / {
        if ($http_referer !~* ^($|http://) ){
             return 403;
        }
        uwsgi_pass unix:/tmp/flask.sock;
    }

    location /restapi/v1/ {
        if ($upstream_location = "master") {
            uwsgi_pass unix:/tmp/flask.sock;
        }
        if ($upstream_location != "master") {
            proxy_pass https://$upstream_location;
        }
    }
}

Works. Perhaps there is another way. If someone prompts - I will be grateful.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question