Search code examples
nginxiframereverse-proxynginx-reverse-proxy

How to configure nginx reverse-proxy to support external site in iframes


I'm in the unfortunate situation that I need to extend my react application with an iframe containing an external application.

My application is hosted by a nginx reverse proxy that handles /api and signalr communication. Unfortunately it also handles the outbout iframe src url.

in this example my site is on the url https://example.com The iframe src url is in this case "https://external-site.com/someapp/session?token=1234" When i see the requests in the browser the url has changed to https://example.com/esternal-site.com/someapp/session?token=1234, which needless to say is not working out of the box.

I've been toying with the nginx configuration but has been unable to just pass the request through without modification. The iframe/destination works as expected when running locally.

I've attempted with a few different configuations inspired by stackoverflow and medium etc. but they've all returned various error codes. the server runs on port 80, but https is handled by ingress on azure.

This is what i have currently:

upstream bff_service {
    server    ${BFF_HOST}:${BFF_PORT};
    keepalive 32;
    keepalive_requests 1000;
    keepalive_timeout 75s;
}

server {
    listen 80;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
        add_header Set-Cookie "msal_client_id=${BFF_MSAL_CLIENT_ID};Path=/;Secure";
    }

    location /api {
        proxy_read_timeout 300s;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host ${BFF_HOST};
        proxy_set_header X-NginX-Proxy true;
        proxy_pass ${BFF_PROTOCOL}://bff_service; 
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_redirect off;
    }

    location ^~ /external-site.com {
        add_header Content-Security-Policy "frame-src 'self' https://external-site.com";
        proxy_pass https://external-site.com/$request_uri;
    }
}

I've also tried adding the lines below to the location:

    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-NginX-Proxy true;

I'm looking for a configuration that allows me to embed an iframe with an external location. Perhaps even avoid nginx proxying it at all?


Solution

  • I ended up making a location in the nginx configuration, where i return a 302 with the request uri with https:/ in front (the request uri is formed as /destination.address.com)

    location ^~ /iframecontent {
        return 302 https:/$request_uri;
    }