Bird
Raised Fist0
Nginxdevops~5 mins

Request/response transformation in Nginx - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you need to change the data coming into your server or the data going out before it reaches the user. Request/response transformation lets you modify these messages easily using Nginx.
When you want to add or change headers in incoming requests to control how your backend handles them
When you need to rewrite parts of the URL before the request reaches your application
When you want to modify the response headers to add security or caching rules
When you want to change the response body, like replacing text or injecting content before sending it to the user
When you want to block or redirect certain requests based on their content
Config File - nginx.conf
nginx.conf
events {}

http {
    server {
        listen 8080;

        location / {
            # Change the Host header in the request
            proxy_set_header Host example.com;

            # Add a custom header to the response
            add_header X-Custom-Response "Transformed by Nginx" always;

            # Rewrite URL path from /oldpath to /newpath
            rewrite ^/oldpath/(.*)$ /newpath/$1 break;

            # Proxy pass to backend server
            proxy_pass http://localhost:9000;

            # Modify response body: replace 'foo' with 'bar'
            sub_filter 'foo' 'bar';
            sub_filter_once off;
        }
    }
}

events {}: Required block for Nginx event handling.

http {}: Main block for HTTP server settings.

server {}: Defines a server listening on port 8080.

location / {}: Handles all requests to the root path.

proxy_set_header Host example.com; changes the Host header sent to the backend.

add_header X-Custom-Response "Transformed by Nginx" always; adds a custom header to the response, including for error responses.

rewrite ^/oldpath/(.*)$ /newpath/$1 break; rewrites URLs starting with /oldpath to /newpath.

proxy_pass http://localhost:9000; forwards requests to a backend server running on port 9000.

sub_filter directives replace all occurrences of 'foo' with 'bar' in the response body.

Commands
Check the Nginx configuration file for syntax errors before applying changes.
Terminal
nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Reload Nginx to apply the new configuration without stopping the server.
Terminal
nginx -s reload
Expected OutputExpected
No output (command runs silently)
Send a request to test the URL rewrite, header changes, and response body transformation.
Terminal
curl -i http://localhost:8080/oldpath/test
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx X-Custom-Response: Transformed by Nginx Content-Type: text/html <html>...bar...</html>
Key Concept

If you remember nothing else from this pattern, remember: Nginx can change both incoming requests and outgoing responses using simple configuration directives.

Common Mistakes
Forgetting to test the configuration with 'nginx -t' before reloading.
This can cause Nginx to fail to reload and stop serving requests properly.
Always run 'nginx -t' to verify syntax before 'nginx -s reload'.
Not enabling 'sub_filter' module or missing 'sub_filter_once off;' when replacing multiple occurrences.
Only the first occurrence of the text will be replaced, leaving others unchanged.
Use 'sub_filter_once off;' to replace all occurrences in the response body.
Using 'rewrite' without 'break' or 'last' flag causing unexpected redirects.
The rewrite may continue processing and cause wrong URL handling.
Add 'break' flag to stop further rewrite processing after the rule.
Summary
Use 'proxy_set_header' to modify request headers before sending to backend.
Use 'add_header' to add or change response headers sent to clients.
Use 'rewrite' with proper flags to change request URLs before processing.
Use 'sub_filter' to modify response body content on the fly.

Practice

(1/5)
1. What is the main purpose of request/response transformation in nginx?
easy
A. To block all incoming requests
B. To increase the server's hardware capacity
C. To change the server's IP address automatically
D. To modify data passing through nginx for better communication

Solution

  1. Step 1: Understand request/response transformation

    This process changes data in requests or responses to improve how clients and servers communicate.
  2. Step 2: Identify the main goal in nginx context

    nginx uses this to modify headers, URLs, or content to suit needs, not hardware or blocking.
  3. Final Answer:

    To modify data passing through nginx for better communication -> Option D
  4. Quick Check:

    Transformation means changing data flow [OK]
Hint: Transformation means changing data in requests or responses [OK]
Common Mistakes:
  • Confusing transformation with hardware upgrades
  • Thinking it blocks requests instead of modifying them
  • Assuming it changes server IP automatically
2. Which nginx directive is used to modify request headers before passing to the backend?
easy
A. add_header
B. proxy_set_header
C. rewrite
D. gzip_disable

Solution

  1. Step 1: Identify directives for header modification

    proxy_set_header changes headers sent to the backend server.
  2. Step 2: Differentiate from other directives

    add_header adds headers to responses, rewrite changes URLs, gzip_disable disables compression.
  3. Final Answer:

    proxy_set_header -> Option B
  4. Quick Check:

    Request header modification = proxy_set_header [OK]
Hint: Use proxy_set_header to change request headers [OK]
Common Mistakes:
  • Using add_header which affects response headers
  • Confusing rewrite with header modification
  • Trying gzip_disable for headers
3. Given this nginx config snippet, what will be the response header X-Transformed value?
location / {
  proxy_pass http://backend;
  proxy_set_header X-Original $http_x_original;
  add_header X-Transformed "Yes";
}
medium
A. Yes
B. $http_x_original
C. No
D. X-Original

Solution

  1. Step 1: Understand add_header directive effect

    add_header adds or modifies response headers sent to the client; here it sets X-Transformed to "Yes".
  2. Step 2: Differentiate proxy_set_header role

    proxy_set_header modifies request headers sent to backend, not response headers.
  3. Final Answer:

    Yes -> Option A
  4. Quick Check:

    add_header sets response header = Yes [OK]
Hint: add_header controls response headers, proxy_set_header controls request headers [OK]
Common Mistakes:
  • Confusing request and response headers
  • Expecting variable names as header values
  • Ignoring add_header effect
4. You want to modify the response body in nginx but changes don't appear. What is the likely cause?
medium
A. gzip compression is enabled, preventing body modification
B. proxy_pass directive is missing
C. add_header directive is used incorrectly
D. server block is missing listen directive

Solution

  1. Step 1: Understand response body modification requirements

    Modifying response body requires disabling gzip compression because compressed data can't be changed easily.
  2. Step 2: Identify common misconfigurations

    If gzip is enabled, changes won't show; proxy_pass or listen missing causes other errors, add_header affects headers only.
  3. Final Answer:

    gzip compression is enabled, preventing body modification -> Option A
  4. Quick Check:

    Disable gzip to modify response body [OK]
Hint: Disable gzip to allow response body changes [OK]
Common Mistakes:
  • Ignoring gzip compression effect
  • Confusing header directives with body changes
  • Assuming missing proxy_pass causes this issue
5. You want to rewrite incoming URLs from /old-path/ to /new-path/ and add a response header X-Updated: true. Which nginx config snippet correctly does both?
hard
A. location /old-path/ { rewrite ^/old-path/(.*)$ /new-path/$1 permanent; add_header X-Updated true; proxy_pass http://backend; }
B. location /old-path/ { proxy_pass http://backend; add_header X-Updated true; rewrite ^/old-path/(.*)$ /new-path/$1 break; }
C. location /old-path/ { rewrite ^/old-path/(.*)$ /new-path/$1 break; add_header X-Updated true; proxy_pass http://backend; }
D. location /new-path/ { rewrite ^/old-path/(.*)$ /new-path/$1 break; add_header X-Updated true; proxy_pass http://backend; }

Solution

  1. Step 1: Choose correct location and rewrite usage

    Rewrite must be inside location matching /old-path/ to rewrite URLs internally with 'break' to stop processing.
  2. Step 2: Add response header and proxy_pass correctly

    add_header adds header to response; proxy_pass forwards request to backend after rewrite.
  3. Step 3: Identify incorrect options

    The config
    location /old-path/ {
      proxy_pass http://backend;
      add_header X-Updated true;
      rewrite ^/old-path/(.*)$ /new-path/$1 break;
    }
    places rewrite after proxy_pass (ignored). Configs using location /new-path/ have the wrong location. Configs with permanent cause redirects, not internal rewrites.
  4. Final Answer:

    location /old-path/ { rewrite ^/old-path/(.*)$ /new-path/$1 break; add_header X-Updated true; proxy_pass http://backend; } -> Option C
  5. Quick Check:

    Internal rewrite + header + proxy_pass = location /old-path/ { rewrite ^/old-path/(.*)$ /new-path/$1 break; add_header X-Updated true; proxy_pass http://backend; } [OK]
Hint: Use rewrite with break inside correct location before proxy_pass [OK]
Common Mistakes:
  • Using permanent instead of break for internal rewrite
  • Placing rewrite after proxy_pass
  • Using wrong location block for rewrite
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard