TechRemarker
TechRemarker

Reputation: 2938

How to redirect attachment URL after permalink change

Say for example a blog permalink structure was (year/month/title)

http://blog.example.com/2012/04/my-title

and now posts permalinks are:

http://blog.example.com/my-title

To make sure Google search results don't break I want to add a .htaccess redirect. Using the Yoast Permalink Redirector generator on their website it suggests adding:

RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/([^/]+)/$ http://blog.example.com/$3

At first glance works great. However WordPress also has attachment urls such as:

http://blog.example.com/2012/04/my-title/my-attachment-url/

That link should be redirected to:

http://blog.example.com/my-title/my-attachment-url/

But it's not when using that Yoast Redirect. Any thoughts on how to update that .htaccess regex to catch attachment urls as well? I'll keep Googling in the mean time. Also can post this on WP Stack Overflow but SO tends to get better answers for server regex htaccess questions.

Upvotes: 0

Views: 532

Answers (1)

Michelle Welcks
Michelle Welcks

Reputation: 3904

I think your regex is basically right. You just need to escape your slashes with a backslash:

^\/([0-9]{4})\/([0-9]{2})\/([^/]+)\/$

Actually to capture your attachment URLs surround your last capturing group that says "match everything that's not a slash greedily", plus the slash, with a new group that match that one more more times greedily:

^\/([0-9]{4})\/([0-9]{2})\/(([^/]+)\/)+$

Also, you can add ?: to groups to make them non-matching.

Upvotes: 1

Related Questions