Reputation: 5947
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?
Upvotes: 3
Views: 2183
Reputation: 8706
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]
Upvotes: 3
Reputation: 40691
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.
Upvotes: 0
Reputation: 18350
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
Upvotes: 1
Reputation: 11080
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
Upvotes: 0