Last-Modified/ETag、查詢字串版本號。<?php
// jsmin.php / cssmin.php 通用邏輯
header("Content-Type: " . (strpos($_SERVER['SCRIPT_NAME'], 'js') !== false
? "application/javascript" : "text/css") . "; charset=utf-8");
if (isset($_GET['get'], $_GET['path'])) {
$files = explode(',', $_GET['get']);
$base = rtrim($_GET['path'], '/') . '/';
$out = '';
foreach ($files as $f) {
$path = $base . $f;
if (is_file($path)) $out .= file_get_contents($path) . "\n";
}
// 簡單壓縮:去空白、換行、註釋
$out = preg_replace('/\s+/', ' ', $out);
$out = preg_replace('/\/\*.*?\*\//s', '', $out); // 多行註釋
$out = preg_replace('/\/\/.*$/m', '', $out); // 單行註釋
echo $out;
}
調用:<script src="jsmin.php?get=jquery.js,app.js&path=js&v=20240101"></script>
缺點:無緩存、無依賴管理、壓縮器簡陋(JS 壓縮易語法錯誤)。
# 方式 A:Composer(推薦) composer require mrclay/minify # 方式 B:手動下載 # https://github.com/mrclay/minify/releases # 解壓後將 min/ 目錄放入 DocumentRoot
<?php $min_documentRoot = $_SERVER['DOCUMENT_ROOT']; // 或手動指定 $min_cachePath = '/tmp/minify_cache'; // 必須可寫 $min_enableBuilder = true; // 啟用構建器界面 $min_allowDebugFlag = true; // 允許 ?debug=1 查看未壓縮 // $min_serveOptions['maxAge'] = 31536000; // 生產環境緩存 1 年
<?php
return [
'js-common' => [
'//js/jquery-3.6.0.min.js',
'//js/bootstrap.bundle.min.js',
'//js/axios.min.js',
'//js/utils.js'
],
'css-common' => [
'//css/bootstrap.min.css',
'//css/fontawesome.min.css',
'//css/app.css'
],
'admin' => [
'//js/admin/dashboard.js',
'//js/admin/table.js',
'//css/admin/theme.css'
]
];
<!-- 單文件(自動壓縮)--> <script src="/min/f=js/utils.js"></script> <link rel="stylesheet" href="/min/f=css/app.css"> <!-- 分組輸出(合並+壓縮)--> <script src="/min/g=js-common&v=20240115"></script> <link rel="stylesheet" href="/min/g=css-common&v=20240115">
v 參數用於緩存破壞,建議用構建版本號或文件修改時間哈希。
# Apache (.htaccess in min/)
RewriteEngine On
RewriteRule ^(.*\.(js|css))$ min/index.php?f=$1 [L,QSA]
RewriteRule ^g=([^&]+) min/index.php?g=$1 [L,QSA]
RewriteRule ^f=([^&]+) min/index.php?f=$1 [L,QSA]
# Nginx
location /min/ {
try_files $uri $uri/ /min/index.php?$query_string;
}
| 場景 | 配置/做法 |
|---|---|
| JS 壓縮報錯 | Minify 預設用 JSMin(保守),可改用 JShrink 或 Terser(需 Node 環境) |
| CSS @import 合並 | 啟用 $min_serveOptions['bubbleCssImports'] = true; |
| 開發調試 | 加 ?debug=1 輸出未壓縮、帶行號源碼 |
| HTTP/2 環境 | HTTP/2 多路復用下合並收益遞減,可改為「小文件不合並、只壓縮」策略 |
| CDN 回源 | 配置 maxAge、ETag,源站開啟 Gzip/Brotli |
Minify 以「零構建、PHP 原生、配置簡單」解決了傳統專案 JS/CSS 合並壓縮痛點。新專請優先採用構建工具鏈;存量專案引入 Minify 可在不改動前端架構前提下,快速獲得 30%-50% 的靜態資源體積減少與請求數降低。