Multitasking with Apache RewriteCond


But one thing I run into a lot is the fact that many applications reference images (or css or js) from the root only. For example, the css files don’t know that I’m running out of /app-1/ and they reference /images/photo.jpg instead of /app-1/images/photo.jpg. Usually those types of path adjustments are best done in the application; but not all apps are enterprise grade.

I stumbled on one way to solve a lot of the problem with Apache’s RewriteCond:

RewriteCond %{REQUEST_URI} ^/(images|js|css)
RewriteCond %{DOCUMENT_ROOT}app-1%{REQUEST_URI} -f
RewriteRule ^(.+)$ app-1/$1 [L,QSA]

RewriteCond %{REQUEST_URI} ^/(images|js|css)
RewriteCond %{DOCUMENT_ROOT}app-2%{REQUEST_URI} -f
RewriteRule ^(.+)$ app-2/$1 [L,QSA]

Basically, it says that if the request starts with “/images”,”/js”,or “/css”, look to see if a file with that name exists within the /app-1/ folder, then look within the /app-2/ folder. If a file with that name does exist, rewrite the url to use that subpath off of localhost.

One downside is if app-1 and app-2 have an image with the same file name, I will see the app-1 version in app-2. But it is a great little hack since I’m usually working with only 2 or 3 codebases in one day.