Today I ran into an odd problem while trying to create permanent redirects on a website to help with search engine optimization. The website I was working on used a fairly standard URL rewrite rule that rewrite all portions of the URL to a querystring and then the application handled the querystring internally. This methodology is common in many CMS systems and also in the popular Codeigniter framework. When I attempted to use standard .htaccess 301 permanent redirects they would add an unexpected querystring to the URL containing the previous URL that we were rewriting.
To illustrate the problem. I was attempting to rewrite /old-page to http://www.website.com/new-page and when the redirection occurred I would get something along the address of http://www.website.com/new-page/?url=old-page.
I couldn’t figure out a solution for the problem using standard redirects such as:
Redirect 301 /old-url http://www.website.com/new-url |
I tried different variations and position and nothing seemed to work. After some experimentation I decided to approach the problem from another direction. Instead I created a RewriteRule to handle the rewriting and then included two designations [L] indicating this is the final rule and to tell apache to stop looking for additional rules if this condition is met and then I specified [R=301] indicating this is 301 redirect. (CAUTION: Do not just use [R] as this is recorded as 302 redirect which is not a preferred redirect type for SEO)
The final redirect looks like this in .htaccess and seems to work as expected.
RewriteRule ^old-url?/?$ http://www.website.com/new-url [L,R=301] |
There are likely other ways to approach this problem but this one is working great for me. Let me know if you have any problems implementing this methodology into your .htaccess file.
Thanks! Exactly what i needed..
Thanks man I am using the codeigniter and running into this issue and I think this is exactly what I am looking for but I have one issue. My old url contains an html extension. I thought the following should work…
RewriteRule ^test\.html?/?$ http://www.example.com/new-url [L,R=301]
but it will result in
http://www.example.com/?/test.html
Any ideas?
Worked like a charm!
Thanks