0

I have changed my permalink to the custom structure /news/%postname% however I am now trying to set up a 301 redirect so if someone types in the old url of http://example.com/this-is-my-post they will automatically be redirect to http://example.com/news/this-is-my-post

I have successfully set up a redirect for my custom post types as I moved all the posts over from the custom post type "events" to "latest" by using this:

RewriteRule ^events/(.*) http://www.example.com/latest/$1 [R=301,L]

However I'm not sure I can use this to redirect the main blog posts without affecting the website pages.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
MV-123
  • 367
  • 2
  • 3
  • 14

2 Answers2

0

To omit the requests for events or latest, you must define an appropriate condition. The rule looks similar to the one you already have

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/events/
RewriteCond %{REQUEST_URI} !^/latest/
RewriteCond %{REQUEST_URI} !^/news/
RewriteRule ^(.*)$ /news/$1 [R,L]

You may also combine the three excluding conditions into one

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/(events|latest|news)/
RewriteRule ^(.*)$ /news/$1 [R,L]

When everything works as it should, you may replace R with R=301 (permanent redirect). Never test with R=301.

Community
  • 1
  • 1
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • I tried this but it is also adding the "news" prefix to my website pages eg. www.example.com/this-is-a-page is now showing as www.example.com/news/index.php. I just need it for my WordPress posts. The pages should still follow the postname permalink structure – MV-123 Mar 30 '17 at 14:40
  • I am not sure, if I really got it, but see the updated answer. If there are even more rules in the current .htaccess, update the question with the rules you have. – Olaf Dietsche Mar 30 '17 at 15:48
0

Step on change your permalink structure in Settings > Permalinks

from /%post-name%/ 

to /news/%post-name%/

Once you are done setting the new link structure Please try this in code you might want copy paste this code in the functions file of your active theme.

https://github.com/devatsemtitans/wp-plugin-snippets/blob/wp_redirect/old-permalinks-redirect

What this code basically does is it caches the slug of your post from the query URL and check if the post exists with that slug in your website then it calls the particular posts permalink and redirects your post to its new URL structure with a 301 status code.