1

I have a WordPress website hosted on Bluehost which contains the following URL pattern:

http://www.example.com/2017/01/30/sample-post/

I want to permanent redirect it to use this:

http://www.example.com/sample-post/

So I opened .htaccess kept in the example.com folder and changed it to this

RewriteEngine On
RedirectMatch 301 ^/([^/]+)/$ http://www.example.com/$1

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Then I went to my Permalink Settings in the Wordpress admin and changed my "Common Settings" from "Day and name" to "Custom Structure" /%postname%/

Now when I access http://www.example.com/2017/01/30/sample-post/ it gives me

404 | Page Not Found! Sorry, but the page you were looking for is not here.

And when I access the URL directly http://www.example.com/sample-post/ it gives me

too many redirects error.

Where am I goofing up?

1
RedirectMatch 301 ^/([^/]+)/$ http://www.example.com/$1

The pattern ^/([^/]+)/$ doesn't match the URL-path /2017/01/30/sample-post/, so these URLs will not be redirected. However, it does match /sample-post/ - which is why you get the redirect loop.

However, RedirectMatch is also a mod_alias directive, not mod_rewrite. (RewriteEngine does not apply.) You should change this to a mod_rewrite directive to avoid potential conflicts and unexpected results. (Different Apache modules execute at different times, despite their apparent order in the config file.)

So, try the following instead:

RewriteRule ^\d{4}/\d\d/\d\d/(.+) /$1 [R=302,L]

This specifically matches a URL of the form /2017/01/30/sample-post/ (the trailing slash is not enforced). Your redirect would have actually stripped the trailing slash.

Make sure your browser cache is cleared before testing. Change the 302 to a 301 only when you are sure it's working OK. (302s avoid being cached.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.