Recently I was challenged by the need to call an Iframe from a front-end API. Trying this without a workaround instantly triggered CORS errors because browsers are protected against calling content from external domains. Of course, I could have avoided CORS by calling the API from the backend, but in this case it wasn’t possible. Also one can avoid CORS temporarily (for testing purposes) by disabling a browser’s security features. For example, I disabled security in OSX Chrome by running the following in terminal:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome –disable-web-security –user-data-dir=~/ChromeUserData/

I needed to permanently address the problem, though, so I eventually settled on a strategy whereby NGINX diverts a local subdomain to an external URL, thus tricking my browser into not throwing the CORS error. (Note that the URL you are calling in as an IFrame must have its header policies set to allow itself to be “Iframed.” If it doesn’t, then overcoming CORS won’t help.)

To illustrate, say that you have a main domain called mydomain.com and you need to access content from outsidedomain.com. Basically, you would set up a rule in NGINX to divert anything that makes a call to your subdomain mydomain.com/outsidelink to actually be diverted to outsidedomain.com.

You add an NGINX location block as such:

location /outsidelink/ { proxy_pass http://outsidedomain.com/}

Now any call to the local subdomain “outsidelink” gets diverted to the external domain.