Mobile app version of vmapp.org
Login or Join
Samaraweera270

: .htaccess and permanent redirection with a special condition I have a WordPress website hosted on Bluehost which contains the following URL pattern: http://www.example.com/2017/01/30/sample-post/ I

@Samaraweera270

Posted in: #301Redirect #Htaccess #ModRewrite #Seo #Wordpress

I have a WordPress website hosted on Bluehost which contains the following URL pattern:
www.example.com/2017/01/30/sample-post/

I wanted to permanent redirect it to use this:
www.example.com/sample-post/

So I opened .htaccess kept in the example.com folder and changed it to the following with the help of a suggestion by w3dk.

RewriteEngine On
RewriteRule ^d{4}/dd/dd/(.+) / [R=301,L]

# 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


After I wrote this rewrite rule, everything of the URL format example.com/2017/01/30/sample-post works great. However, there are a few URLs in the website that have the format example.com/name-of-category/2008/10/20/sample-post and are throwing a 404 as the result of the above rewrite rule.

I want to permanently redirect example.com/name-of-category/2008/10/20/sample-post to example.com/name-of-category/sample-post.
What change do I need to make in my .htaccess file?

10.01% popularity Vote Up Vote Down


Login to follow query

More posts by @Samaraweera270

1 Comments

Sorted by latest first Latest Oldest Best

 

@Ogunnowo487

To handle category posts of the form /name-of-category/2008/10/20/sample-post then include something like the following directive after the existing redirect.

RewriteRule ^([a-z-]+)/d{4}/dd/dd/(.+) // [R=301,L]


This would redirect /name-of-category/2008/10/20/sample-post to /name-of-category/sample-post. Note that the category consists of just the lowercase a-z and the - (hyphen), as in your example.

If you needed to allow more characters in the category then changing [a-z-] to [w-] in the above RewriteRule pattern would allow a-z, A-Z, 0-9, _ and -. But it is better to be as restrictive as possible.

So, in summary:

RewriteEngine On
RewriteRule ^d{4}/dd/dd/(.+) / [R=301,L]
RewriteRule ^([a-z-]+)/d{4}/dd/dd/(.+) // [R=301,L]

:

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme