Ben
Ben

Reputation: 1022

htaccess redirect if url contains a specific word

A site i'm working on had news articles sitting within a latest news directory.

/news/latestnews/some-article-2012.html

These have now been moved in to different directories depending on the year of the news article. So 2013 are now within:

/news/2013/some-article-2013.html

and 2012 are in:

/news/2012/some-article-2012.html

I can easily latestnews to one of the directories using:

RewriteRule ^news/latestnews/(.*)$ /news/2011/$1 [R=301,L]

But i need to redirect to the specific year directory. All news articles contain the year in name. So some-article-2012 or some-article-2013.

Any help on adjusting my rule to also check the year.

Thanks

=========EDIT=======

I've managed to add some RewriteCond to redirect to the correct directory but having trouble appending the requested file name.

So using this rule

RewriteCond %{REQUEST_URI} ^/news/latestnews/(.*)$
RewriteCond %$1 ^(.*)2012(.*)$
RewriteRule ^(.*)$ /news/2012 [R=301,L]

This url

/news/latestnews/some-article-2012.html

gets redirect to

/news/2012 

but the "some-article-2012.html" is missing from the url.

I've tried adding $1 to the end of the rewriterule so you have:

    RewriteRule ^(.*)$ /news/2012$1 [R=301,L]

But the the full old url gets appended so you have:

/news/2012/news/latestnews/some-article-2012.html

Upvotes: 3

Views: 18329

Answers (1)

Ben
Ben

Reputation: 1022

Ok I can't take the full credit for this, as it was by a user on another forum where i'd posted, but thought i'd share in case it helps someone on here.

RewriteCond %{REQUEST_URI} ^/news/latestnews/(.*)$
RewriteRule ^news/latestnews/(.*)(201[0-9])(.*)$ /news/$2/$1$2$3 [R=301,L]

This will actually deal with all years from 2010.

Upvotes: 10

Related Questions