We’re migrating our blog to WordPress and need to set up 301’s for all the pre-existing URL’s.
The existing structure from root is as follows:
/blog/bid/148509/The-Role-of-a-Father
What we need to have it do is go to
/the-role-of-a-father
(from root) on our new WordPress blog.
Some of the problems I’m having are the following:
- I do not know how to do a
RewriteRule
that keeps the original ending slug the same. - The numbers after
/bid/
are never consistant, and so I need something that ignores those numbers but does not ignore the title slug afterwards. - I need the final URL to convert to lowercase.
I know this is quite a lot to ask for. Any help and resources would be very helpful!
Through a lot of research looking into the syntax, regex, and variable info I was able to figure out how to do this.
To help others who also might be new to .htacces, rewrites, and/or regex, I’m posted my solution, as well as what I learned.
The final product that solved my problem:
The full .htaccess looks like this:
Basically what I did was use some regex magic on the pattern. Since the numbers after
/bid/
always changed, using regex I can say “match this pattern no matter what numbers are in it” This is done using[0-9].*
[0-9]
matches any character that is numbered 0-9..
matches any single character and*
matches 0 or more instances of that character.The next part is where the magic happens. The slug (permalink) after that is matched by
.*
and when wrapped in()
is saved as a variable.I can then use that variable in the substitution portion of my rewrite. The
$1
is the variable that represents the(.*)
in the pattern section. If you had more sections wrapped in()
then you could use$1
,$2
, and so on to used saved variables from the initial pattern.Once that was done I set my flags:
R=301
sets the header redirect telling search engines that the content has moved permanently.L
is the last rule that is applied when that pattern is matched (ie. don’t keep trying to match rewrites).NC
specifies that capitalization doesn’t matter.Note
Pay special attention to the spacing of your rules. Not having enough or having too many could cause your entire website to go down. It’s especially important to know that in the flags section, there are no spaces between the commas. That bit me.
When migrating a blog, you need to use a 301 redirect.
301 redirects, by definition, will change the path in the url bar.
From memory, you’ll need to do all of these steps if you need to make it lowercase too.
In your VirtualHost, add
RewriteMap lc int:tolower
In your .htaccess, add: