Last active
October 10, 2022 16:01
-
-
Save mashhoodr/0640e3cbdf007029af725091b6493eb0 to your computer and use it in GitHub Desktop.
A simple proxy pass script for Cloudflare Worker which handles the basic cases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
/** | |
* Respond to the request | |
* adapted from https://github.com/xiaoyang-liu-cs/workers-proxy | |
* @param {Request} request | |
*/ | |
async function handleRequest(request) { | |
let upstream_domain = "example.com"; | |
let upstream_path = "/"; | |
let response = null; | |
let url = new URL(request.url); | |
let url_host = url.host; | |
let url_hostname = url.hostname; | |
let method = request.method; | |
let request_headers = request.headers; | |
let new_request_headers = new Headers(request_headers); | |
url.protocol = 'https:'; | |
url.host = upstream_domain; | |
if (url.pathname == '/') { | |
url.pathname = upstream_path; | |
} else { | |
url.pathname = upstream_path + url.pathname; | |
} | |
new_request_headers.set('Host', url_host); | |
new_request_headers.set('Referer', 'https://' + url_hostname); | |
let original_response = await fetch(url.href, { | |
method: method, | |
headers: new_request_headers, | |
body: request.body, | |
redirect: 'manual' | |
}); | |
let response_headers = original_response.headers; | |
let new_response_headers = new Headers(response_headers); | |
// used for debugging | |
new_response_headers.set('st-cloudflare-hit', 'true'); | |
let status = original_response.status; | |
return new Response(original_response.body, { | |
status, | |
headers: new_response_headers | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment