2/13/2008

Redirecting while changing file extensions with .htaccess

We had a folder of files on the old server that were mixed HTML and PHP. On the new server these were all PHP and we needed the old HTML files to change to this new extension.

Redirect: http://www.socengine.com/seo/guide/anyfile.html
To: http://www.strongwind89.com/articles/anyfile.php

Redirect: http://www.socengine.com/seo/guide/anyfile2.php
To: http://www.strongwind89.com/articles/anyfile2.php

Solution:

Add the following directive:
RedirectMatch 301 /seo/guide/(.*)\.(php|html) http://www.strongwind89.com/articles/$1.php

Explanation:

(*.) matches zero or more of any character and saves it as the back-reference $1. \.(php|html) tells apache to match a period followed by either “php” or “html” and saves it as the back-reference $2 (although we won’t be using it in this example). Notice we had to escape the period with a backslash. This is to ensure apache does not interpret the period as meaning “any character” but rather as an actual period. Enclosing “php” and “html” in parenthesis and separating them with a pipe “|” character means to match either one of the values. So if it were to say (php|html|css|js|jpg|gif) the regex would match any of the files with the extensions php, html, css, js, jpg, or gif.

Also, if for some reasons we needed to preserve the name of the extension we matched, it would be stored as the back-reference $2. Back-references are incremented in accordance with how many sets of parenthesis are in the regular expression.

11 comments:

Gabriel de Kadt said...

Hi nice tip but no joy on my server. I found this works:

RewriteEngine On
RewriteBase /
RewriteRule ^(.*).html$ $1.php [R=301]

Friv said...

Thanks for sharing!

Y8 said...

Nice blog post! Thank you.

Friv said...

Great blog. I love this blog

Y8 said...

That fantastic! realy! these website is way better then everything I ever saw. Thanks admin.

Friv said...

The site design is very good and good sections.. Very well done

Girls Games said...

It is a nice web, i like it

Y8 said...

Thanks, I understand now.
I know it would have helped me, and others.

Y8 games said...

good information, thanks for sharing!

y8 games said...

thanks for post.Nice Blog.

quocvinh said...

thank you very much
y8 games ,y3 games

Live Page Popularity