Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 467
Ben Avatar asked Jan 24 '26 04:01

Ben


1 Answers

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.

like image 52
Ben Avatar answered Jan 27 '26 01:01

Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!