Search code examples
web-servicesnginxserverwebserver

How can I intercept all outgoing responses within nginx and modify them?


I have a nginx server that serves a forum via php. I want to add an upstream to nginx that intercepts all responses generated by the php application and modifies the response.

Is it possible to achieve this by modfying the nginx conf file?

Here is my existing configuration:

server {
    listen 443 ssl;
    server_name example.net www.example.net;
    index index.php index.html;
    root /var/www/html;

    location / {
        try_files $uri $uri/ /index.php?$uri&$args;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass xf2-php-fpm:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME     $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

How can I modify this configuration to pass all responses generated by php to an upstream?


Solution

  • You could add a new upstream block outside of your current ones that defines the server/servers you want to use as the upstream

    upstream upStream{
        server upStream_server:4000;
    }
    

    Then modify the location block that handles PHP requests to proxy the requests to the upstream server

    location ~ \.php$ {
        proxy_pass http://upStream; #URL to which the request should be proxied
        proxy_set_header Host $host; #Hostname of the server to which the request is being sent to
        proxy_set_header X-Real-IP $remote_addr; #IP address of the client that made the request
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #IP address of the client that made the request and any other IP addresses that the request was forwarded through
        //
    }
    

    This should pass all requests to the upStream server and the response will be sent back to the client. Tell me if you need more help