Forum Moderators: phranque

Message Too Old, No Replies

.htaccess to make a separate root directory for files

         

SlappyTheFish

10:18 am on Nov 22, 2007 (gmt 0)

10+ Year Member



Hello.

In my root folder I have an index.php file which processes all the page request for my web application. The requests come in the form of /welcomepage/ and are rewritten to index.php?page=welcomepage in .htaccess.

However, if a request for a files comes in, for example "/css/default.css", I'd like it to look in a separate folder for these public files, e.g. /public/ so the request above, it would return the file /public/css/default.css

I have this at the beginning of my .htaccess file:

RewriteCond public/%{REQUEST_URI} -f
RewriteRule ^(.+)$ public/$1 [QSA,L]

The idea is that if the file exists in the public folder, then it is returned.

Rails does a similar thing, but it checks to see if the file exists in the actual root and if not then it returns the file from the public folder. The problem is, if the file doesn't exist in the public folder then error 500 is returned, which RoR handles with a standard "Something went wrong" message which I don't think is really very good.

I was reading in the Apache rewriting guide (http://httpd.apache.org/docs/1.3/misc/rewriteguide.html), there is an example which looks to me as if it does the same thing:

# first try to find it in custom/...
# ...and if found stop and be happy:
RewriteCond /your/docroot/dir1/%{REQUEST_FILENAME} -f
RewriteRule ^(.+) /your/docroot/dir1/$1 [L]

Does anyone have any idea why my arrangement isn't working?

Thanks.

jdMorgan

12:55 pm on Nov 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Most likely because you are using a URL-path as a filename, which probably won't work. You'll likely need to include the DOCUMENT_ROOT path.

RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -f

Take care with the slashed in the 'built-up' filepath. For example, REQUEST_URI will always return a leading slash, so original code will have been looking for public//<requested_URI>

Figuring out what is wrong with the pathname and/or other internal variables is often difficult. It's sometimes handy to modify the rule temporarily so that it does an external redirect with the problematic variable appended as a query string -- the sole purpose being to make it visible to you in your browser address bar.

For example, if your rule fails with the modified RewriteCond, add this rule temporarily:


# If my path doesn't exist
RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} [b]![/b]-f
# Copy my path to %1 variable
RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} (.*)
# And redirect to make my browser show it to me
RewriteRule . http://www.example.com/?bad_path=%1 [R=302,L]

Jim