Using javascript fetch in worker

I writing a worker that fetches content from a subdomain to provide it as content for a different subdomain. The problem is that I don’t want to publish the alternate domain name on DNS. Is there a way to bind an IP address to the domain name from within the worker thereby bypassing DNS?

Another solution might be to fetch from the origin web server using an IP address while providing the desired subdomain information in the request header (in theory).

I would greatly appreciate it if you could point me in the right direction.

I need some clarification is your goal to use the worker to serve content as domain A from a different domain domain B but use an IP address for domain B. If so, then you can just use the IP address for the URL of the fetch request from the worker.

I think you have the general idea. The problem with using an IP address
is that the web server has more than one virtual domain being served at
the same IP address. The worker needs to communicate to the web server
which domain is desired.

Then you just need to set the Host Header to the domain that you want.

I will try that today. However, I have read that it is one of the
“forbidden” headers to set:

Is there some reason why it would work in a worker but not generally?
Just curious.

I ran a local test ($ wrangler dev)
I got an unexpected response: error code: 1003

I believe this is Cloudflare error code…
“Error 1003 Access Denied: Direct IP Access Not Allowed”

Hi there! You cannot modify the host header in Cloudflare Workers nor can you directly use an IP address in fetch(). You will have to create a DNS record for a subdomain pointing to the desired IP address and use that subdomain when making sub-requests. You can avoid exposing the IP address by proxying :orange: the subdomain. Furthermore, you can create a Firewall Rule blocking anyone directly visiting the subdomain - then use fetch(request, {cf: {resolveOverride: 'subdomain.example.com'}} in your Worker. This will send the request to the IP address of the subdomain.

2 Likes

I think this Cloudflare community article says it all…

Hi @user42111
Is there a reason why you can’t do what @albert has directed and also add a “ServerAlias” to your Apache vhost?

Yes. I believe this is the best solution possible.

Thank you.

I cannot use “ServerAlias” because ‘host A’ (the host where content needs to come from) requires a different version of PHP from ‘host B’ (the host where browsers visit). I am not allowed to use more than one version scripting language per virtual domain instance. ServerAlias would cause the incompatible version used for ‘host B’ to be applied to web pages in ‘host A’.

It was the first thing I looked into and I think it could have been a great solution. A dead end, unfortunately.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.