Mod rewrite redirection to another domain if file not exist

拈花ヽ惹草 提交于 2019-12-12 19:00:13

问题


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


回答1:


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




回答2:


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]


来源:https://stackoverflow.com/questions/12748813/mod-rewrite-redirection-to-another-domain-if-file-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!