gpt4 book ai didi

php - 可以把js和css放到public文件夹外吗?

转载 作者:行者123 更新时间:2023-12-04 06:51:12 29 4
gpt4 key购买 nike

如何将我的 JS 和 CSS 文件放在公用文件夹之外?我有一个图书馆,我希望我的所有网站都可以使用它,并且为了便于更新,将它放在特定网站的公共(public)文件夹之外,以便所有人都可以轻松阅读。这是否可能,或者我是否需要将其全部托管在另一个域上(我宁愿不轻松)。

htaccess 可能吗?

最佳答案

适当扩展 Jamie Wong 的回复:

您可以使用充当 Controller 的 PHP 文件轻松地做到这一点 - 但您还必须记住发送正确的内容 header ,否则浏览器可能无法识别 CSS。

您还需要一些安全检查以确保没有文件遍历

// /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;

您可以更进一步,设置 .htaccess 重写以将 CSS 请求(如/css/main.css)映射到此 Controller :

RewriteEngine On
RewriteRule ^css/(*.).css$ /style.php?sheet=$1 [L]

关于php - 可以把js和css放到public文件夹外吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3097824/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com