Rewriting/redirecting to external domain

In my nginx config, prior to switching to caddy, I had this rewrite rule:

location /blog { rewrite ^/blog(.*)$ https://user.gitlab.io$1 last; }

I tried

rewrite { r /blog(.*) to https://user.gitlab.io{1} }

and

redir /blog(.*) https://user.gitlab.io{1} 

But neither of these work, rewrite is apparently specifically for internal urls, and redir doesn’t seem to support regex…

So, how can one rewrite/redirect urls to external resources?

Hi @DanielFGray,

redir is indeed a bit limited in functionality when it comes to manipulating the destination based on details of the request.

Luckily, if you only need to manipulate the URI, not the hostname (which would always be https://user.gitlab.io), we can cheat a little to make that happen with a rewrite first (rewrite always occurs before redir in the request processing chain).

example.com {

  # First, strip '/blog' from the URI
  # This populates the {rewrite_uri} placeholder
  rewrite /blog {
    r ^/blog(.*)$
    to {1}
  }

  # Then, if we started with '/blog', redirect
  # The {uri} placeholder contains the original URI
  redir {
    if {uri} starts_with /blog
    to https://user.gitlab.io{rewrite_uri}
  }
}
1 Like

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