How to use caddy as a forward proxy

Trying to proxy connections from another server

In nginx I’d do it with something like
server {
listen 80;
server_name my.host-ip.whatever;
location / {
access_log off;
proxy_pass https://my-public-website-address:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host srv1.botstack.host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

How do I do something similar in caddy?
Here’s my caddyfile for reference

https://my-public-address {
gzip {
ext *
level 9
}
tls email
header / {
Omitted because useless for this question
}
proxy my-host-ip my-public-address
browse
}

I still have no clue how to do this in caddy. How can I reverse proxy with the proxy directive? Currently it just says connection refused

Hi @anupritaisno1, welcome to the Caddy community.

Perhaps I’m mistaking it, but it seems to me like the nginx configuration you posted is set to listen on your IP address (server_name my.host-ip.whatever) and reverse proxy to your public website address over HTTPS (proxy_pass https://my-public-website-address), which seems odd to me.

Anyway, from the documentation for proxy:

Because nginx’s location is /, that’s what you want for a base path here. Add in the headers, and it should look something like this:

proxy / [upstream hostname/IP address] {
  header_upstream Host srv1.botstack.host
  header_upstream X-Real-IP {remote}
  header_upstream X-Forwarded-For {remote}
}

Now, the problem with your proxy directive at the moment is that you’ve got your IP address as a base path. That means, effectively, that Caddy won’t proxy unless you request https://my-public-address/my-host-ip. However, the browse directive means that if it’s not proxying, it should be showing you what’s in the site root (which you haven’t set, so the site root is whichever directory Caddy is running in - it’s best to set root /path/to/www/html whenever you’re using browse).

The fact you’re getting “connection refused” makes me think that possibly you are trying to access your site over HTTP while you’ve configured Caddy only to listen for HTTPS connections to this site. If that’s the case, and you want Caddy to upgrade HTTP->S automatically, just remove the scheme from my-public-address and Caddy will take care of both.

https://caddyserver.com/docs/proxy
https://caddyserver.com/docs/placeholders

1 Like

Hi guys I’ve resolved my issue the thread can be closed

Thanks for showing me the right place to look at

What did you do to resolve it?

It was just an error in the way I used the proxy directive

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