regex.htaccessurl-rewritinghttp-status-code-404forward

.htaccess forward local to remote on 404


I do all of my development locally on sites that use a CMS. We have a directory that is used to store user-uploaded content, such as images (/assets/). The problem is, when developing locally, I don't want all of the uploaded files from the production site on my machine, so I leave this directory empty, and all of the HTTP requests for files in the /assets/ directory get 404'ed.

What would be great is if I could have a rewrite rule in my .htaccess that detects the 404, and forwards to the external URL of the production site to load the asset from there. The logic would be:

Request localhost/somesite/assets/foo.jpg
200 response ? send the local file /somesite/assets/foo.jpg
404 ? forward to http://www.productionsite.com/assets/foo.jpg

Is this possible?


Solution

  • Have your .htaccess rules like this:

    Options +FollowSymlinks -MultiViews
    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(assets/.*)$ http://www.productionsite.com/$1 [R,L,NC]
    

    This will make sure that any request matching /assets/ and doesn't already exist on your local webserver will be externally redirected to http://www.productionsite.com/assets/...