Redirect / to reverse proxy at path

So I bought a domain nanop.us for my node app called “nanopush”. To have the url spell out the app name I want it hosted at nanop.us/h/. I’ve accomplished as much with this Caddyfile:

nanop.us/h/ {
    proxy / localhost:3000 {
        transparent
    }
    header / {
        # Enable HTTP Strict Transport Security (HSTS) to force clients to always
        # connect via HTTPS (do not use if only testing)
        Strict-Transport-Security "max-age=31536000;"
        # Enable cross-site filter (XSS) and tell browser to block detected attacks
        X-XSS-Protection "1; mode=block"
        # Prevent some browsers from MIME-sniffing a response away from the declared Content-Type
        X-Content-Type-Options "nosniff"
        # Disallow the site to be rendered within a frame (clickjacking protection)
        X-Frame-Options "DENY"
    }
    gzip
}

nanop.us/ {
    # Needed to make relative urls in the app stay within /h/
    redir /h /h/
}

I still need to redirect nanop.us/ to nanop.us/h/ so the root still takes you to the app. But since / represents all endpoints for the redir rule, I don’t know how to tell it to only redirect /.

After hours of tinkering I found a config that worked for me.

The key was adding a redirect like this:

redir /h/ {
    if {path} is /
}

The whole caddy file looks like this now:

nanop.us/h/ {
    proxy / localhost:3000 {
        transparent
    }
    header / {
        # Enable HTTP Strict Transport Security (HSTS) to force clients to always
        # connect via HTTPS (do not use if only testing)
        Strict-Transport-Security "max-age=31536000;"
        # Enable cross-site filter (XSS) and tell browser to block detected attacks
        X-XSS-Protection "1; mode=block"
        # Prevent some browsers from MIME-sniffing a response away from the declared Content-Type
        X-Content-Type-Options "nosniff"
        # Disallow the site to be rendered within a frame (clickjacking protection)
        X-Frame-Options "DENY"
    }
    gzip
}

nanop.us/ {
    redir /h /h/
    redir /h/ {
        if {path} is /
    }
}
1 Like

Huh. I always figured it’d have to take the form:

redir {
    if {path} is /
    / /h/
}

Guess I just assumed with an open subdirective block Caddy would take the first argument to redir as a redirect code.

That’s pretty much the current accepted method of getting around Caddy assuming / to be catch-all, though.

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