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

Trouble with regex redirect

Started by Muut Archive 9 years ago · 3 replies · 472 views
9 years ago

Hi, I hope someone can help or at least tell me if what I'm trying to do is possible or not.

I have a site with pages such as:
http://example.com/Getting-started

and I'm moving to a layout with versions for top level navigation, like:
http://example.com/1.0/Getting-started
http://example.com/1.1/Getting-started
etc.

I wanted to use a redirect so if anyone tried the http://example.com/Getting-started url, it would put them to the 1.1 version at http://example.com/1.1/Getting-started. The following works for pages that exist:

TXT
redirects:
  /(.*): '/1.1/$1'

However if I purposely try a url for a page that doesn't exist (such as 'http://example.com/Getting-started/blah') the browser window crashes and I see a ERR_TOO_MANY_REDIRECTSerror and the url looks like:
http://example.com/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/1.1/Getting-started/blah

I thought maybe my redirect regex was too general and could be causing that loop, so I tried a more specific one:

TXT
redirects:
  /(Getting-started.*): '/1.1/$1'

Again this works for "Getting-started" pages that exist, but if the page doesn't exist it triggers the ERR_TOO_MANY_REDIRECTSerror again.

Is it possible to do what I'm trying to do? To have a redirect like this without losing the general 404 functionality on urls which match the regex but don't have a page?

Thanks in advance!

9 years ago

The way you have it, it matches everything, and always rewrites it to prepend with /1.1 hence your infinite loop problem.

What you need to do is match on anything that doesn't already start with /1.1 using a negative lookahead:

https://regex101.com/r/FQsxpS/2

so you would have:

TXT
redirects:
  ^(?!\/1.1)(.*)$ : /1.1/$1

Try that.

9 years ago

Actually:

TXT
redirects:
  '^(?!/1\.1)/(.*)$': '/1.1/$1'

Of course this only is triggered if the original page is not found at the path requested.

9 years ago

Thank you, rhukster! That helped a lot. I suspected my regex was off. Much appreciated!

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1336 9 years ago
Archive · by Muut Archive, 9 years ago
2 926 9 years ago
Archive · by Muut Archive, 9 years ago
2 4056 9 years ago
Archive · by Muut Archive, 9 years ago
1 2941 9 years ago
Archive · by Muut Archive, 9 years ago
3 1112 9 years ago