Redirecting old URLs

From snippet wiki
Jump to navigation Jump to search

In case you move your website to a new structure and you are unable to keep the up and running url scheme: The Apache module rewrite is your friend.

You can create a simple textfile with two columns, one with the old path and one with the new path:

MyOld/Path/info.html thevery/newpath/article/

Note the missing leading / in front of the URLs! You have to skip that if defining the mapping within the .htaccess. If you define it in the virtual host section you might need them again.

And withing the .htaccess file you can use a mapping file:

RewriteRule ^(.+)$ /${mappingfile:$1} [R=301,L]

Remember to define the mappingfile within the virtual host configuration of your domain. You can't do that within a .htaccess file.

RewriteMap mappingfile txt:/path/to/file/map.txt

Thos URLs not found in that map are translated to a default value beeing the empty string resulting in a redirect to your homepage. That might be the desired action. Otherwise you have to restrict the mapping to only a part of matching patterns. In that example all old URLs started with an uppercase letter:

RewriteCond %{REQUEST_URI} ^/([A-Z])
RewriteRule ^(.+)$ /${mappingfile:$1} [R=301,L]

If there are more old URLs you can add some OR conditions:

RewriteCond %{REQUEST_URI} ^/([A-Z]) [OR]
RewriteCond %{REQUEST_URI} ^/(someoldprefix|evenmoreoldpath)
RewriteRule ^(.+)$ /${mappingfile:$1} [R=301,L]