Ward
Ward

Reputation: 3318

Redirect Regex for URLs

I have a Wordpress site and I'd like to redirect traffic based on specific criteria. I'm using a redirect plugin that has a Source URL (which can be a regex) and a Destination URL that can contain the result from the regex such as $1.

/blog/{slug} should redirect to /{slug} but only when {slug} is not ?page= or page/{anything}

So /blog/the-article-name will redirect to /the-article-name but /blog/?page=3 will not redirect and /blog/page/3 will not redirect.

Also, /blog/category/{slug} should redirect to /{slug}.

Thanks

Upvotes: 0

Views: 1116

Answers (1)

Ward
Ward

Reputation: 3318

I was able to figure it out after some trial and error:

^/blog\/(?!.*(page\/.*|\?paged=))+(.+)

I can access the 2nd match (the slug) using /$2

https://example.com/blog/the-article-slug will match for group 2 and redirect to https://example.com/the-article-slug

https://example.com/blog/page/2 will not match for group 2 https://example.com/blog/?paged=2 will not match for group 2

I'm using another redirect rule, ^/blog/category/(.*) to match the slug which I can access using /$1

https://example.com/blog/category/the-article-slug will match for group 1 and redirect to https://example.com/the-article-slug

Hope this helps someone else

Upvotes: 1

Related Questions