Skip to content
Grav 2.0 is officially stable. Read the announcement →
Installation & Hosting

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

Started by colin avolve 7 years ago · 0 replies · 927 views
7 years ago

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

TXT
example.com/year/month/date/blog-title

For example

TXT
example.com/2008/09/11/my-thoughts-on-life

In Grav, the new URL is

TXT
example.com/blog/my-thoughts-on-life

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

TXT
/(.*)/(.*)/(.*)/(.*): /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.

Suggested topics

Topic Participants Replies Views Activity
Installation & Hosting · by antoinep, 2 months ago
8 605 1 month ago
Installation & Hosting · by Jürgen Dietrich, 8 months ago
0 371 8 months ago
Installation & Hosting · by rappluk, 9 months ago
0 422 9 months ago
Installation & Hosting · by N, 1 year ago
3 351 1 year ago
Installation & Hosting · by Youle, 1 year ago
1 282 1 year ago