Home > Article > Operation and Maintenance > How Nginx distributes through the identity in the header
Nginx can distribute requests to different servers based on the customized identifier in the request header. Specifically, you can use the map directive to map the custom identifier in the request header to a different backend server address, and then use the proxy_pass directive to forward the request to the corresponding backend server.
The following is a sample configuration file:
http { map $http_my_header $backend { default backend1.example.com; value1 backend2.example.com; value2 backend3.example.com; } upstream backend1 { server 192.168.1.1:8080; server 192.168.1.2:8080; } upstream backend2 { server 192.168.2.1:8080; server 192.168.2.2:8080; } upstream backend3 { server 192.168.3.1:8080; server 192.168.3.2:8080; } server { listen 80; server_name example.com; location / { proxy_pass http://$backend; } } }
In this configuration file, we define a map directive to map the $http_my_header variable in the request header to different backend server addresses. If the value of $http_my_header is value1, the request will be forwarded to backend2.example.com; if the value of $http_my_header is value2, the request will be forwarded to backend3.example.com; otherwise, the request will be forwarded to backend1.example.com.
Next, we define three upstream blocks, representing the backend server groups backend1, backend2, and backend3. Each group contains multiple backend servers. In the server block, we use the proxy_pass directive to forward the request to the corresponding backend server.
After this configuration, if the value of $http_my_header in the request header is value1, the request will be forwarded to the backend2 backend server group; if the value of $http_my_header is value2, the request will be forwarded to the backend3 backend server. group; otherwise, the request will be forwarded to the backend1 backend server group.
Configure socket and add several configurations:
server { listen 80; server_name example.com; location /websocket { proxy_pass http://$backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } }
The above is the detailed content of How Nginx distributes through the identity in the header. For more information, please follow other related articles on the PHP Chinese website!