When we recently decided to redesign our website, we came across the issue of keeping the visitors flow from our old pages and links. As best practice for SEO, we had to redirect our old links to the new ones. The obvious decision was to simply use “Redirect 301” in our .htaccess, but that messed up our subdomains.
1 |
Redirect 301 ^/index\.php$ /index.html #this would usually do, but not in this case |
After some research it became clear that the answer was mod_rewrite (for those of you not familiar with this practice, here is a useful article about url rewriting). The trick was to use a rewrite condition for your root domain, so that the redirection applies only to it.
1 2 3 4 |
RewriteEngine on RewriteCond %{HTTP_HOST} ^(www\.)?if-act\.net$ [NC] #this is the condition RewriteRule ^/index\.php$ /index.html [R=301,NE,L] #this applies if the condition is true RewriteRule ^/contacts\.php$ /#contacts [R=301,NE,L] #redirection to an anchor |
So the “RewriteCond” compares %{HTTP_HOST} variable (for the php gurus out there %{VAR} variables correspond to php $_SERVER[‘VAR’] variables) and redirects only if true. It is important to pay attention to the flags after the rewrite rule. The “R=301” flag states that this is a permanent redirection (best practice for SEO) and the “L” flag tells the server that it shouldn’t look at any other rules after this one. Also essential when dealing with hashes in the redirecition process is to use the “NE” flag, which tells the server not to escape special chars.
It is also important to look at the case when you want to redirect a link with a query portion (that’s the string after the query sign – ‘?’) to another with hash (‘#’) in it. As the server doesn’t take notice of the query portion it will simply append it to the new URL.
1 |
RewriteRule ^/services\.php\\?seo$ /#services [R=301,NE,L] #redirect to /#services?seo |
Since we don’t want that, we need to add a new query to our redirected link, which will override the old one. So you end up with a rule like this:
1 |
RewriteRule ^/services\.php\\?seo$ /?#services [R=301,NE,L] #works just fine |
So this is our tip of the day and hopefully this will save you some keyboard smashing moments the next time you try to SEO-friendly redirect pages. 🙂
Leave any questions, remarks and suggestions in the comment section below.
Cheers! Have a nice day!