I wanted to rename a part of this website and I knew, I needed a 301 in order to redirect people from the old to the new address. It was easy to find out that this can be achieved through .htaccess and the basic needs were also pretty easy to gather. Create a text-file called .htaccess on your apache-web-server in the root directory of your website. It needs to contain the following two lines to switch the module on:
RewriteEngine on
RewriteBase /
Then, for the actual rule there’s a lot of generally helpful stuff out there – only it didn’t help me:
- the string in question was a GET-variable as part of a dynamic URL
- the string could be in the middle of the URL or at the end
My task was to replace a chunk from a dynamic URL and leave unchanged whatever was before or after this chunk.
The example was the page you’re reading at the moment. It used to be called »Recettes« and I wanted to rename it to »Recipes«.
The overview was reached through http://www.brasserie-seul.com/?Recettes, but this article had the URL http://www.brasserie-seul.com/?Recettes&nr=60. In addition this page has groups, so there is also http://www.brasserie-seul.com/?Recettes&group=web, […]group=ubuntu etc.
It took me literally hours of research, until I finally found Carolyn Shelby’s very helpful article. Her code took me almost there:
RewriteCond %{QUERY_STRING} ^(.*)Recettes(.*)$
RewriteRule ^$ Recipes? [R=301,L]
This would take any URL containing the string »Recettes«, no matter where in the url it was, replace it with »Recipes« – and loose everything that followed. Now, Carolyn’s last example contains something she could have been doing if her strings were consistent:
RewriteCond %{QUERY_STRING} ^review=(.*)$
RewriteRule ^cgi-bin/script.cgi$ restaurants/%1? [R=301,L]
The interesting bit here is %1
in the rule, because it apparently represents the (.*)
from the condition. In my example I have two (.*)
‘s: one before the string, one after. It is Regex for »any character or no characterlaquo. When I figured out that the first (.*)
could be addressed through %1
and the second through %2
, I was finally there:
RewriteEngine on
RewriteBase /
RewriteCond %{QUERY_STRING} ^(.*)Recettes(.*)$
RewriteRule ^$ ?Recipes%2 [R=301,L]
Thank you, Carolyn Shelby.
Leave a Reply