Skip to content

Instantly share code, notes, and snippets.

@paulgibbs
Last active August 19, 2024 09:49
Show Gist options
  • Select an option

  • Save paulgibbs/6f2a944552fc9bfbd7e530f150362a8f to your computer and use it in GitHub Desktop.

Select an option

Save paulgibbs/6f2a944552fc9bfbd7e530f150362a8f to your computer and use it in GitHub Desktop.
Cloudflare reverse proxy via workers - generated by ChatGPT
export default {
async fetch(request, env, ctx) {
return handleRequest(request)
}
}
async function handleRequest(request) {
const url = new URL(request.url)
if (url.pathname.startsWith('/app2/')) {
url.hostname = 'server2.example.com'
url.protocol = 'https'
url.port = ''
const newHeaders = new Headers(request.headers)
newHeaders.set('Host', request.headers.get('Host')) // Equivalent to proxy_set_header Host $host
newHeaders.set('X-Real-IP', request.headers.get('CF-Connecting-IP') || request.headers.get('X-Real-IP'))
newHeaders.set('X-Forwarded-For', request.headers.get('CF-Connecting-IP') || request.headers.get('X-Forwarded-For'))
newHeaders.set('X-Forwarded-Proto', request.headers.get('X-Forwarded-Proto') || url.protocol)
const newRequest = new Request('https://the-other-server.example.com', {
method: request.method,
headers: newHeaders,
body: request.body,
redirect: 'manual'
})
const response = await fetch(newRequest)
return response
}
return fetch(request)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment