Caddy rewrite based on User-Agent not working

711 Views Asked by At

I'm trying to rewrite a path if the requested client is a mobile user. As per caddy documentation, this code should redirect a mobile user to the specified destination.

rewrite /redirect-me {
    if {>User-Agent} has mobile
    to /redirected
}

But it's wont when I add the User-Agent condition. I tried other condition which works just fine. I tried to look for caddy available directives like User-Agent but can't find a single hint.

2

There are 2 best solutions below

1
On

I think it is likely {>User-Agent} is case sensitive.

try {>User-agent} and see if that works.

0
On

I recently ran into a similar issue and wanted to share a solution that worked for me on Caddy 2.6.1. I used a named matcher to match requests that are both from a mobile device and are directed to /redirect_me. Here is the relevant portion of the Caddyfile:

@mobile {
    # Check if the string "mobile" is in the User-Agent portion of the request header.
    header_regexp User-Agent (?i)(mobile)

    # Only match the request if it is to the /redirect_me path.
    path /redirect_me
}

# Rewrite the previous request to the desired path.
rewrite @mobile /redirected