Jonathan Huet
Jonathan Huet

Reputation: 131

Mod rewrite redirection to another domain if file not exist

What I'm trying to do:

I need to redirect a request to a file to another domain if the file not exists. For example:

http://www.mydomain.com/js/foo.js 

redirects to (if not exists)

http://www.myanotherdomain.com/js/foo.js

What I do:

I wrote the next lines at the end the htaccess, but they redirect ALL!

RewriteCond %{REQUEST_URI} !-f
RewriteRule ^(.*)$ http://www.myanotherdomain.com/$1 [L,NC]  

Before these lines, I have a lot of lines like this (I'm using MVC (Model, View,Controller)):

RewriteRule ^car/brand/?$ ?controller=Car&action=viewBrand [L,NC]  

What happens:

It works wells with non existing files, but seems to be imcompatible with the MVC rules. These rules have to match and then stop evaluating rules because de "L" flag. But it seems to continue evaluation of the rules and finally evaluates the redirect rule. The result is this:

http://www.mydomain.com/car/brand/

goes to

http://www.myanotherdomain.com/?controller=Car&action=viewBrand

Please can anyone help me?

Thank you very much,

Jonathan

Upvotes: 2

Views: 1254

Answers (2)

Jon Lin
Jon Lin

Reputation: 143906

Try placing these rules after your MVC rules:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.(js|png|jpe?g|gif|css|html?)$ http://www.myanotherdomain.com/$1.$2 [L,R,NC]

If you want all requests, and not just static content like scripts and images then change the RewriteRule line to:

RewriteRule ^(.*)$ http://www.myanotherdomain.com/$1 [L,R,NC]

Upvotes: 0

Solo
Solo

Reputation: 726

Try this:

RewriteCond %{REQUEST_FILE} !-f
RewriteRule ^(.*)$ http://www.myanotherdomain.com/$1 [QSA,R,L]

See also: mod rewrite directory if file/folder not found

Upvotes: 1

Related Questions