Serving different roots from a wildcard host

I have a domain on my site, review.jvt.me, which is currently being hosted by Nginx, and the config can be found at the bottom of the post. The specifics are not important, but it enables me to have the following:

  • if I put a folder feature-review into some pre-defined path, I can access it on feature-review.review.jvt.me
  • these paths are not known up-front, as they are dynamically deployed

I was wondering if there was some way to achieve the same functionality in Caddy?

Nginx config:

# /etc/nginx/sites-enabled/review.jvt.me
server {
    listen 80;
    server_name ~^(www\.)?(?<sname>.+?).review.jvt.me$;
    root /srv/www/review.jvt.me/review.jvt.me/review/$sname/current/site;

    index index.html;
    error_page 404 /404.html;

    charset utf-8;

    access_log /var/log/nginx/review.jvt.me-access.log;
    error_log  /var/log/nginx/review.jvt.me-error.log debug;
}

I use something similar for developing sites locally on a Macbook with Apache.

<Virtualhost *:80>
  VirtualDocumentRoot "/Users/whitestrake/Projects/www/%1"
  ServerName sites.test
  ServerAlias *.test
  UseCanonicalName Off
</Virtualhost>

Unfortunately I don’t believe this is possible in Caddy.

The next release of Caddy is getting {labelN} placeholders, like {label1} to mean whatever value is in the first label of *.example.com. That should make rewriting it in Caddy pretty trivial, no?

When those go live, I expect this setup would work:

*.example.com {
  root /var/www/example.com
  rewrite {
    to /{label1}{uri}
  }
}

To access an example file /var/www/example.com/foo/bar.jpg when browsing to foo.example.com/bar.jpg.

2 Likes

Bingo. That should work in the next release.

(Edit: Except you’ll have to enable either on-demand TLS for a cert, or the DNS challenge to get a wildcard cert.)

This has been implemented here: https://github.com/mholt/caddy/pull/2072

2 Likes

Ah, my understanding of rewrite was that it only worked on the actual URI, not in terms of the path on disk.

So just to confirm, I should be able to have, in the new version, the following:

*.review.jvt.me {
  root /srv/www/review.jvt.me/review.jvt.me/review
  rewrite {
    to /{label1}/current/site{uri};
  }
}

?

Basically – except lose the semicolon in your rewrite :wink:

1 Like

You’re actually right about that - it does, in fact, only work on the URI… technically speaking.

The trick works because when figuring out what file to serve to the client, web servers take the webroot - for the sake of example, lets say /var/www/html - and add the URI, lets say /foo/bar.jpg - to get a final result of /var/www/html/foo/bar.jpg off the host’s disk.

1 Like

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