HTML template based on useragent

Would someone give be a little direction on how I would direct caddy to use a specific HTML template for browse based off of the user agent?

I want to direct some machine scrappers (specific agent)
on my caddy to a basic template that ive created vs everyone else to see the standard caddy browse one.

I think I need to use rewrite but not sure exactly how with a HTML template.

OK, uhh… yeah, I think we can do this with some creative rewrite usage. We can’t have a dynamic browse template in the same site definition, but we can rewrite to proxy to a different site definition internally.

example.com {
  # First rewrite-proxy
  # For User-Agent "foo"
  rerwite {
    if {>User-Agent} is foo
    to /foo{uri}
  }
  proxy /foo/ localhost:2015 {
    without /foo
  }

  # Second rewrite-proxy
  # For User-Agent "bar"
  rerwite {
    if {>User-Agent} is bar
    to /bar{uri}
  }
  proxy /bar/ localhost:2016 {
    without /bar
  }
}

localhost:2015 {
  # Listener for User-Agent "foo"
  internal
  root /var/www/html
  browse / /path/to/template/foo.tpl
}

localhost:2016 {
  # Listener for User-Agent "bar"
  internal
  root /var/www/html
  browse / /path/to/template/bar.tpl
}
1 Like

Are you sure it can’t be done with browse templates? The way I understand the question, they just want to use a different browse template for bots vs. browsers. Since browse supports all standard template actions (plus some others), you can do something like {{if eq (.Header "User-Agent") "user agent here"}}...{{end}}, right?

2 Likes

Well actually now I’m not so sure it can’t be done :stuck_out_tongue:

I think you could indeed combine both templates into one template file and determine which one to render based on the template action, like your example.

I was too busy thinking in scope of Caddyfile that I forgot that templating had that kind of functionality.

Hmm. Yes. I do want a different template for bot vs human like Matt said. I’d like to use caddy’s built in browse template though for human.

If I do this within the browse template {{ if eq…}} Then I can hand the bot a specific template which is good. However now that caddy has directed that user to the custom template, I don’t think I can use the default caddy one which is nicer than I’d e able to write. If I had two custom templates I think @matt I could use that approach which would be better than rewriting to proxy. Or am I just missing how to serve the default if I did that.

I’d suggest doing what all great artists do:

1 Like

Ah insert face palm that’ll work. Let me give this a try. Thanks a lot

1 Like

That was simply enough. Thanks for the help.

1 Like

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