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

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

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 · 792 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, 15 hours ago
5 61 9 hours ago
Installation & Hosting · by Jürgen Dietrich, 7 months ago
0 63 7 months ago
Installation & Hosting · by rappluk, 8 months ago
0 62 8 months ago
Installation & Hosting · by N, 12 months ago
3 73 12 months ago
Installation & Hosting · by Youle, 1 year ago
1 62 1 year ago