views:

583

answers:

2

I have links which has an old format as www.mydomain.com/dir/this_my_page.html and my new script needs to be forwarded to www.mydomain.com/newdir/this+my+page.htm... What am I going to edit in my .htaccess file so this can be made possible? Can anyone help me with the mod_rewrite function of the htaccess?

+2  A: 

I suggest using a Front controller. This means that you use the htaccess file to rewrite ALL requests to a single file (index.php) and then you use code in that file to dispatch to the appropriate page. You can do a redirect from the old URLs to the new URLs, and if it's a new url then you dispatch to the appropriate page controller.

This would be way easier than writing huge rewrite rules for each type of page you might have. And this way all of the work is done in the same language your site is already running, so you don't have to learn and maintain a horrible huge .htaccess file which tends to be a nightmare to work with anyway!

Here is an example of an .htaccess file that redirects all non-static requests to index.php:

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php

Then in index.php you need to do all of the logic of interpreting the request and figuring out what to do with it. Personally I like to use the Zend Framework MVC: http://framework.zend.com/manual/en/zend.controller.html

But that could be a lot of work to convert to if you already have it in a different format.

OverloadUT
I'm lost here. how am I going to do that? thanks!
+1  A: 

If you're just changing parts of the URL, e.g. directories, you can use

RedirectMatch ^/oldPath/(.*) http://www.example.com/newPath/$1

(might work with relative urls, not tested...)

If the document names also change you either have to figure out an algorithm to translate or place one redirection for each url you want to redirect. Depending on the number of documents you could do the non-magical and completely uncool

RedirectMatch ^/dir/first_document.html /newdir/first+document.html
RedirectMatch ^/dir/second_document.html /newdir/second+document.html
RedirectMatch ^/dir/third_document.html /newdir/third+document.html

Some Regexp wizard probably can add regexps for all numbers of underscores to be translated to plusses, but I'll leave that open ;)

If that's too much, you don't actually need to rewrite, you could also opt for a 404 error document, e.g.

ErrorDocument 404 /redirect.php (or .jsp, .asp, .whatever)

Then use that script to lookup the original request url and use your favourite scripting/programming language to translate old urls to new urls (examine the request headers to figure out what the original URL is named. In PHP place in the error document (don't forget to remove it in production version) and find the original URL header in the request. Then send a 301 Moved Permanently Response with the new URL.

Olaf