Redirect requests inside html page to go through proxy

Viewed 107

I have a proxy, and I've fetched contents of the webpage I need, like https://google.com. However, I need to be able to then also redirect all the other requests for resources to go through the proxy. So, all images and scripts go back through the proxy. Additionally, all links also go back through the proxy. How can I access all of the requests and do this? Would this be through modifying the HTML of the site? Now, I should be able to serve the contents of any dynamic or static site on a localhost, without having certain elements and scripts not loading.

2 Answers

Your question states that you have a proxy, but your answer implies that you are implementing a proxy.

It sounds like you're asking for a Node.js solution, since question was tagged node.js and notice says

The answer needs to detail how to implement this in NodeJS, and provide working code examples.

In Node.js, you can achieve this using HTTP Party's http-proxy library

Install it with npm install http-proxy.

Then match routes using your web framework, and rewrite the requests as needed.

In Express:

const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxyServer({
  autoRewrite: true,  //rewrites the location host/port
  changeOrigin: true, //change "Origin" header
}); 

app.use('/api/v1/',(req, res, next) => {
  //redirect requests from `https://api.your.domain/api/v1/` to `https://api.your.domain/api/v2/`
  //subpaths like /api/v1/me will also be changed (e.g. `/api/v2/me`)
  proxy.web(req, res, {target: 'https://api.your.domain/api/v2/'}, next );
});


So I found the solution!

Using a service worker I can redirect requests to go back through the forward proxy. This example proxies requests from an old api version to a new one (this isn't what Im doing though. It would add a certain url, like https://api.allorigins.win/get?url= to the beginning):

self.addEventListener('fetch', e => {
  const {url} = e.request;
  if(url.includes('https://api.your.domain/api/v1/') {
    const newUrl = url.replace('/api/v1/', '/api/v2/');
    e.respondWith(fetch(newUrl));
  }
});

This article essentially fixes my problem: https://betterprogramming.pub/how-to-run-a-proxy-server-inside-your-browser-8b96ea2ef1ea

Related