tags:

views:

58

answers:

4

Hi

How can I put my JS and CSS files outside the public folder? I have a library that I'd like all my websites to use and for easy updating, have this outside a particular website public folder so it can be easily read by all. Is this possible or do I need to host it all on another domain (I'd rather not for ease).

htaccess possibly?

A: 

different domain/website will work. it's impossible for the web server to give out something that is not in the public folder.. you might want to create a virtual host

kgb
with Apache rewrite module and proper controller logic, you can do this easily
HorusKol
+1  A: 

You can do this in a kind of awkward manner by having a proxy that grabs the files for you.

You could have a php file that acts as a placeholder for these scripts like so:

www.example.com/style.php?sheet=main

that reads a file you have in

/home/your_user/main.css

through file_get_contents

WARNING

Be very sure that the style.php script doesn't have access to anything outside the folder you specify. This is can be a massive security hole

Jamie Wong
A: 

JS and CSS files would be requested by the web browser. In otherwords, the browser has no understanding of your server directory structure...it just needs a valid URI.

Easiest solution would be to set up a subdomain: mycdn.example.com and put your JS and CSS files there and have each site reference that directly.

DA
+2  A: 

To properly expand on Jamie Wong's response:

You can easily do this using a PHP file acting as a controller - but you must also remember to send the correct content headers otherwise the browser might not recognised the CSS for what it is.

You also need a bit of security checks to make sure there's no file traversal

// /public_html/style.php

$cssDir = realname(dirname(__FILE__) . '/../css/';

if (!isset($_GET['sheet'])) {
  header('HTTP/1.1 404 Not Found');
  exit;
}

$file = realpath($cssDir . $_GET['sheet'] . '.css');
if (!$file) {
  header('HTTP/1.1 404 Not Found');
  exit;
}

if (substr($file, 0, strlen($cssDir) != $cssDir) {
  // because we've sanitized using realpath - this must match
  header('HTTP/1.1 404 Not Found'); // or 403 if you really want to - maybe log it in errors as an attack?
  exit;
}

header('Content-type: text/css');
echo file_get_contents($file);
exit;

You can go further than this, and set up .htaccess rewrites to map CSS requests like /css/main.css to this controller:

RewriteEngine On
RewriteRule ^css/(*.).css$ /style.php?sheet=$1 [L]
HorusKol
+1 For the mod_rewrite. Always meant to look into how to do that, but never bothered since I learned rails.
Jamie Wong
Rewrite is the way forward, although instead of file_get_contents ill probably just include. Thanks
Ashley
true - the use of include allows you to use PHP code in the 'stylesheet' so you can set up parameterised colours and so on (something lacking in CSS)
HorusKol