Using proxy_set_body in NGINX

nginx proxy set body
07 April 2025

Using proxy_set_body in NGINX

If you are working with NGINX, you may have heard of the module name ngx_http_proxy_module. This module allows you to proxy requests to other servers. One of the interesting features of this module is the proxy_set_body directive that enables you to modify the request body before sending it to the target server.

For example, suppose you have an application web that connects to an API and you want to modify some parameters before sending the information to the API server. By using proxy_set_body, you can easily accomplish this task.

The way to use this directive is inside a block `location`, where you can define it. This configuration allows you to have more control over a request that is being proxied to another server. However, be aware that this directive should come after other proxy directives like proxy_pass.

In continuation, we will review a simple example of using proxy_set_body. By using this example, you will be able to understand how to modify the request body and send it to the target server.

Code Example

location /api {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_body "{\"key\": \"new_value\"}";
}

Code Explanation

Now, we will explain the lines of code:


location /api {

This line specifies that the settings within this block will apply to the route /api.


proxy_pass http://backend;

In this line, requests are sent to the server with the name backend.


proxy_set_header Host $host;

This directive sets the Host header to ensure the correct hostname is sent to the target server.


proxy_set_body "{\"key\": \"new_value\"}";

Here, the request body is modified and converted into a new JSON that contains the new value for the key.


This way, you can easily use proxy_set_body to change requests before sending them out to achieve better management over proxies!

FAQ

?

How can I modify the request body?

?

Can I set multiple headers?

?

Does proxy_set_body only work for JSON?

?

How does the proxy request flow in NGINX work?

?

Can I send more complex data?