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.
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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.