questions

Regex to exclude varying part of a URL in redirection

Rate this post

I’m looking to redirect images on a WordPress install as such:

From:

https://example.com/uploads/folder/123/image.jpg
https://example.com/uploads/folder/123/image-small.jpg
https://example.com/uploads/folder/123/image-medium.jpg
https://example.com/uploads/folder/123/image-large.jpg

To a unique:

https://example.com/wp-content/uploads/image.jpg

The goal is to have all the variations (normal, small, medium and large) to redirect from that old folder to a unique image in the new one. I have been able to achieve that with the Redirection plugin, using a series of Regex:

/uploads/folder/\d{1,3}/(.*).jpg
/wp-content/uploads/$1.jpg

/uploads/folder/\d{1,3}/(.*)-small(.*)
/wp-content/uploads/$1$2

/uploads/folder/\d{1,3}/(.*)-medium(.*)
/wp-content/uploads/$1$2

/uploads/folder/\d{1,3}/(.*)-large(.*)
/wp-content/uploads/$1$2

But that seems not efficient, and I would like to have one regex to rule them all…

I tried different ways to unify all the cases in one Regex but couldn’t do it (the ways of excluding I found wouldn’t allow me to pass the $1 and $2 to rewrite the URL properly). I know this is probably very basic, but I would really appreciate if someone could point me in the right direction.

 

✔️Solution:

This may work:

/uploads/folder/\d{1,3}/(.*?)(?:-small|-medium|-large)?(\.\w+)
/wp-content/uploads/$1$2

Note that . in regex means any character, and regex quantifiers are greedy by default (e.g. matching as far as possible). So having .* is often calling for trouble.

Leave a Reply

Your email address will not be published.

Back to top button