I want to use .htaccess on an Apache server to redirect only calls to the server that are not files or folders in the filesystem. For example, if the server gets a request for:

http://www.domain.tld/page1.html

And page1.html is not an actual file on the server, it should 301 redirect to:

http://new.domain.tld/page1.html

Otherwise, it should not do anything. Is this possible? If so, how? Please provide some example code if possible. The code I currently have is:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.domain\.tld [NC]
Rewriterule ^(.*)$ http://subdomain.newdomain.tld/$1 [L,R=301]

While this does the redirect, it doesn't ignore actual files and folders on the server.

link|improve this question
feedback

2 Answers

up vote 1 down vote accepted

Here's the tested solution:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.domain\.tld [NC,OR]
RewriteCond %{HTTP_HOST} ^domain\.tld [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Rewriterule ^(.*)$ http://subdomain.newdomain.tld/$1 [L,R=301]

Lines 3 & 4 tell apache to apply the rule when the request comes with a www or not, without regard to capital or lower-case letters. The !-f and !-d at the ends of lines 5 & 6 respectively tell apache to avoid applying the redirect to existing files and directories.

link|improve this answer
feedback

You can do this using Apache's mod_rewrite, which allows you to redirect requests using the RewriteRule directive. You can make this conditional on a file existing using the RewriteCond directive. The mod_rewrite documentation is probably a good place to start.

link|improve this answer
Read the section on special RewriteCond patterns, such as -f and -d. If you show me how you've tried using these and what sort of behavior you encountered, I'll provide some suggestions on how to fix it. – larsks Jul 2 '11 at 21:36
Thanks for the tip. – el Rafa Jul 9 '11 at 10:54
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.