Redirect /category/caddy to /categories/caddy where caddy is dynamic

Hi,

I am trying to switch over to Caddy from Apache. I currently have the following in my Apache .htaccess file:

RewriteCond %{REQUEST_URI} ^/category/(.*)
RewriteRule ^category/(.*)$ https://%{HTTP_HOST}/categories/$1 [R=301,L]
RewriteCond %{REQUEST_URI} ^/tag/(.*)
RewriteRule ^tag/(.*)$ https://%{HTTP_HOST}/tags/$1 [R=301,L]

Essentially what it is doing is it is redirecting all /category/$1 traffic to /categories/$1 and all /tag/$1 traffic to /tags/$1.

I was reading the documentation for Caddy redir and rewrite, but I’m not quite sure how to accomplish the task because both require exact matches on the source.

I also tried this:

rewrite {
    if {uri} match ^/category/(.*)
    r  ^category/(.*)$
    to /categories/{1}
}

Am I missing something obvious? Preferably I’d like to have a 301 redirect so search engines know that /category/ and /tag/ has permanently moved to their plural alternative.

Please let me know.

Thanks,

This part might be a problem. The URI starts with a forward slash, so this won’t match.

Also, you’re using regex twice - first to match ^/category/(.*), then to capture the same. This means your if statement is wholly redundant and doubles up on regex processing for every incoming request. Try this:

rewrite {
  if {uri} starts_with /category/
  r ^/category/(.*)$
  to /categories/{1}
}

The comparison starts_with is a substring check. This method lets you get away with avoiding regex at all unless it’s actually required for the rewrite.

For tag → tags:

rewrite {
  if {uri} starts_with /tag/
  r ^/tag/(.*)$
  to /tags/{1}
}

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