Search code examples
phpapache.htaccessmod-rewritehttp-redirect

.htaccess redirect to external url but with mod_rewrite


I have two webspaces and one domain. In one of the webspaces, I have approximately 5 TB of audio files and images, while the other webspace is reserved for scripts.

Here's the problem I'm facing:

Let's say my webspaces' URLs are 'domain1.tld' and 'domain2.tld'.

All my files and other assets are located on 'domain2.tld'. I've only uploaded the PHP files to 'domain1.tld'.

The issue arises when I want to access a video, for example, located at 'domain2.tld/files/video01.mp4,' but the link mistakenly shows 'domain1.tld/files/video01.mp4.' How can I configure it so that if the file doesn't exist on 'domain1.tld,' it automatically redirects to 'domain2.tld'?

I found a similar question here, and the provided solution looks like this:

     Options +FollowSymLinks -MultiViews
    # Turn mod_rewrite on
     RewriteEngine On
     RewriteBase /
    
     RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.com$ [NC]
     RewriteRule ^subdirectory/?$ http://newurl.com [L,R=301,NC]

However, this solution has one problem:

If I go to http://domain1.tld/%FILE% and the file doesn't exist, it should redirect to http://domain2.tld/%FILE%. Is it possible to achieve this using mod_rewrite?

In essence, I want it so that if 'domain1.tld/%FILE%' doesn't exist, it automatically accesses 'domain2.tld/%FILE%'.

Thanks!


Solution

  • Try that:

    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)$ http://domain2.tld/$1 [L,R=302,NC]
    

    It means: if file or directory or symlink not found here, do redirect to domain2.tld .

    (It's 302 because testing new rewrite rules with permanent redirect is dangerous )