Skip to content

Commit

Permalink
add workers.dev domain support
Browse files Browse the repository at this point in the history
  • Loading branch information
seadfeng committed Aug 5, 2024
1 parent 43eaea2 commit fcfa981
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ Free domain name application:
const currentDomain = "example.com";
```

#### Use workers.dev default domain?

This method only supports single domain reverse proxy.

Here is the code:

[workers.dev/index.js](workers.dev/index.js)

```js
// replace to your proxy site domain
const proxySite = 'example.com';
```

### 3. deploy to workers

```sh
Expand Down
50 changes: 50 additions & 0 deletions workers.dev/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
const url = new URL(request.url);
const host = url.host;

if (url.pathname === '/robots.txt') {
const robots = `User-agent: *
Disallow: /
`;
return new Response(robots,{ status: 200 });
}


const proxySite = 'www.proxysites.ai';
const urlPath = url.pathname;
const origin = `https://${proxySite}`;
const actualUrl = new URL(`${origin}${urlPath}${url.search}${url.hash}`);

const modifiedRequestInit = {
method: request.method,
headers: request.headers,
redirect: 'follow'
};

if (!['GET', 'HEAD'].includes(request.method)) {
const requestBody = await request.clone().arrayBuffer();
modifiedRequestInit.body = requestBody;
}

const modifiedRequest = new Request(actualUrl, modifiedRequestInit);

const response = await fetch(modifiedRequest);

let body = await response.arrayBuffer();
const contentType = response.headers.get('content-type');

if (contentType && (contentType.includes('text/') || contentType.includes('application/x-javascript'))) {
let text = new TextDecoder('utf-8').decode(body);
text = text.replace(new RegExp( proxySite, 'g'), host );
body = new TextEncoder().encode(text).buffer;
}

const modifiedResponse = new Response(body, response);
modifiedResponse.headers.set('Access-Control-Allow-Origin', '*');
return modifiedResponse;

}

0 comments on commit fcfa981

Please sign in to comment.