An example using regex for URL redirects [301] (for a site migrated from Wordpress)


I recently converted a blog from Wordpress to Grav, and the URLs for individual (blog) posts changed as a result. I needed a solution so as to not lead to 404 page not found errors.

I am posting my (current) solution here for anyone who is looking, as I was not able to find a direct and detailed/specific how-to. I have some formal coding experience, years working with Drupal and WordPress (mostly as a theme), though am relatively new to Grav and twig.

I looked at options for redirecting (301 redirects) rather than URL aliases as these are a permanent change, and wanted search engines to update with the new URLS.

The typical URL’s on the WordPress site were

For example

In Grav, the new URL is

What I have in my site.yaml folder is the following, under ‘redirects:’

/(.*)/(.*)/(.*)/(.*): /blog/$4[301]

The first part, before the colon, is the existing URL. The second part is the new URL in Grav (i.e. where I want to redirect to).

My understanding, taking into account I am not very familiar with regex, is that

  • (.*) is a wildcard that represents what I wanted to replace: one each for year, month, date and title.

  • ‘blog’ is in the new URL

  • $4 represents the fourth item ($argument) in the existing URL (i.e. ‘my-thoughts-on-life’)

  • [301] is the redirect code, which is stripped from the URL

Someone may have a more elegant solution, or even point out shortcomings of this one.

From my testing, it works and removes any need to manually add ~200 individual URL redirect to site.yaml for this site.