【js&css文件压缩】php+minify+nginx 的配置和使用 -1

时间:2021-02-17 03:48:21

最近没有更新博客,并不是因为没有学习,而是因为没有学到一定程度。不过有些比较工具类的知识却可以拿来小结一下,比如这次所说的文件压缩。
我们都知道web服务器在处理这样的静态文件如图片,js,css的时候所需要的等待时间是十分长的。因此出现了许多的技术来减少传送时间。大家都有接触过xxx.min.js或者xxx.min.css这类的文件.这些文件存储在服务器上.表示已经被工具进行压缩了.不过我们也可以通过服务器脚本将请求的css文件或者js文件压缩后传送。这就是我们要说的minify模块。
minify是一个开源的github项目,可以点击查看项目地址
至于php与nginx的配置可以参考网络上其他的教程,我们这里就不多介绍。当然可以使用apache或其他服务器。
关于minify的目录如下图所示:
【js&css文件压缩】php+minify+nginx 的配置和使用 -1
这里我们可以阅读README.txt和MIN.txt。里面有一定的介绍。
如果需要进行版本升级可以阅读UPGRADING.txt。
我们将min文件夹拷贝到网站根目录(目录可自定),这时候可以通过http://localhost/min/ 就能访问到min文件夹下的index.php文件。
如果使用了某某框架导致无法访问min文件夹下的xxx.php文件,可以设置rewrite机制开启访问(暂无具体写法)。接下来我们要做的就是阅读一下index.php文件
Index.php

<?php /** * Front controller for default Minify implementation * * DO NOT EDIT! Configure this utility via config.php and groupsConfig.php * * @package Minify */ define('MINIFY_MIN_DIR', dirname(__FILE__)); // set config path defaults 配置文件分别是正式用,测试用以及文件组合用 $min_configPaths = array( 'base' => MINIFY_MIN_DIR . '/config.php', 'test' => MINIFY_MIN_DIR . '/config-test.php', 'groups' => MINIFY_MIN_DIR . '/groupsConfig.php' ); // check for custom config paths if (!empty($min_customConfigPaths) && is_array($min_customConfigPaths)) { $min_configPaths = array_merge($min_configPaths, $min_customConfigPaths); } // load config 读取配置文件 require $min_configPaths['base']; // 如果请求中包含 test的关键字 则使用test-config 配置 if (isset($_GET['test'])) { include $min_configPaths['test']; } require "$min_libPath/Minify/Loader.php"; Minify_Loader::register(); Minify::$uploaderHoursBehind = $min_uploaderHoursBehind; Minify::setCache( isset($min_cachePath) ? $min_cachePath : '' ,$min_cacheFileLocking ); // 压缩文件的根目录 可在config.php文件中配置 默认为网站根目录 if ($min_documentRoot) { $_SERVER['DOCUMENT_ROOT'] = $min_documentRoot; Minify::$isDocRootSet = true; } $min_serveOptions['minifierOptions']['text/css']['symlinks'] = $min_symlinks; // auto-add targets to allowDirs foreach ($min_symlinks as $uri => $target) { $min_serveOptions['minApp']['allowDirs'][] = $target; } if ($min_allowDebugFlag) { $min_serveOptions['debug'] = Minify_DebugDetector::shouldDebugRequest($_COOKIE, $_GET, $_SERVER['REQUEST_URI']); } if ($min_errorLogger) { if (true === $min_errorLogger) { $min_errorLogger = FirePHP::getInstance(true); } Minify_Logger::setLogger($min_errorLogger); } // check for URI versioning if (preg_match('/&\\d/', $_SERVER['QUERY_STRING']) || isset($_GET['v'])) { $min_serveOptions['maxAge'] = 31536000; } // need groups config? 请求为g 文件组合 if (isset($_GET['g'])) { // well need groups config $min_serveOptions['minApp']['groups'] = (require $min_configPaths['groups']); } // serve or redirect if (isset($_GET['f']) || isset($_GET['g'])) { if (! isset($min_serveController)) { $min_serveController = new Minify_Controller_MinApp(); } Minify::serve($min_serveController, $min_serveOptions); } elseif ($min_enableBuilder) { header('Location: builder/'); exit; } else { header('Location: /'); exit; } // 不存在f或者g请求 则不输出任何内容

我们需要配置和查看一下config.php文件
config.php

<?php
/** * Configuration for "min", the default application built with the Minify * library * * @package Minify */


/** * Allow use of the Minify URI Builder app. Only set this to true while you need it. */
$min_enableBuilder = false;

/** * If non-empty, the Builder will be protected with HTTP Digest auth. * The username is "admin". */
$min_builderPassword = 'admin';


/** * Set to true to log messages to FirePHP (Firefox Firebug addon). * Set to false for no error logging (Minify may be slightly faster). * @link http://www.firephp.org/ * * If you want to use a custom error logger, set this to your logger * instance. Your object should have a method log(string $message). */
$min_errorLogger = false;


/** * To allow debug mode output, you must set this option to true. * * Once true, you can send the cookie minDebug to request debug mode output. The * cookie value should match the URIs you'd like to debug. E.g. to debug * /min/f=file1.js send the cookie minDebug=file1.js * You can manually enable debugging by appending "&debug" to a URI. * E.g. /min/?f=script1.js,script2.js&debug * * In 'debug' mode, Minify combines files with no minification and adds comments * to indicate line #s of the original files. */
$min_allowDebugFlag = true; //开启调试,可以在浏览器查看错误信息,正式用时需要关闭


/** * For best performance, specify your temp directory here. Otherwise Minify * will have to load extra code to guess. Some examples below: */
$min_cachePath = 'c:\\WINDOWS\\Temp'; //这里我将minify生成的压缩文件缓存到了指定的文件夹下
//$min_cachePath = '/tmp';
//$min_cachePath = preg_replace('/^\\d+;/', '', session_save_path());

/** * To use APC/Memcache/ZendPlatform for cache storage, require the class and * set $min_cachePath to an instance. Example below: */
//require dirname(__FILE__) . '/lib/Minify/Cache/APC.php';
//$min_cachePath = new Minify_Cache_APC();


/** * Leave an empty string to use PHP's $_SERVER['DOCUMENT_ROOT']. * * On some servers, this value may be misconfigured or missing. If so, set this * to your full document root path with no trailing slash. * E.g. '/home/accountname/public_html' or 'c:\\xampp\\htdocs' * * If /min/ is directly inside your document root, just uncomment the * second line. The third line might work on some Apache servers. */
 //设置了目标压缩文件的起始目录
$min_documentRoot = $_SERVER['DOCUMENT_ROOT'].'/Public';
//$min_documentRoot = substr(__FILE__, 0, -15);
//$min_documentRoot = $_SERVER['SUBDOMAIN_DOCUMENT_ROOT'];


/** * Cache file locking. Set to false if filesystem is NFS. On at least one * NFS system flock-ing attempts stalled PHP for 30 seconds! */
$min_cacheFileLocking = true;


/** * Combining multiple CSS files can place @import declarations after rules, which * is invalid. Minify will attempt to detect when this happens and place a * warning comment at the top of the CSS output. To resolve this you can either * move the @imports within your CSS files, or enable this option, which will * move all @imports to the top of the output. Note that moving @imports could * affect CSS values (which is why this option is disabled by default). */
$min_serveOptions['bubbleCssImports'] = false;


/** * Cache-Control: max-age value sent to browser (in seconds). After this period, * the browser will send another conditional GET. Use a longer period for lower * traffic but you may want to shorten this before making changes if it's crucial * those changes are seen immediately. * * Note: Despite this setting, if you include a number at the end of the * querystring, maxAge will be set to one year. E.g. /min/f=hello.css&123456 */
$min_serveOptions['maxAge'] = 1800;//设置客户端缓存的时间长度 1800/60/60=0.5h


/** * To use CSSmin (Túbal Martín's port of the YUI CSS compressor), uncomment the following line: */
//$min_serveOptions['minifiers']['text/css'] = array('Minify_CSSmin', 'minify');


/** * To use Google's Closure Compiler API to minify Javascript (falling back to JSMin * on failure), uncomment the following line: */
//$min_serveOptions['minifiers']['application/x-javascript'] = array('Minify_JS_ClosureCompiler', 'minify');


/** * If you'd like to restrict the "f" option to files within/below * particular directories below DOCUMENT_ROOT, set this here. * You will still need to include the directory in the * f or b GET parameters. * * // = shortcut for DOCUMENT_ROOT */
//$min_serveOptions['minApp']['allowDirs'] = array('//js', '//css');

/** * Set to true to disable the "f" GET parameter for specifying files. * Only the "g" parameter will be considered. */
$min_serveOptions['minApp']['groupsOnly'] = false;


/** * By default, Minify will not minify files with names containing .min or -min * before the extension. E.g. myFile.min.js will not be processed by JSMin * * To minify all files, set this option to null. You could also specify your * own pattern that is matched against the filename. */
//$min_serveOptions['minApp']['noMinPattern'] = '@[-\\.]min\\.(?:js|css)$@i';


/** * If you minify CSS files stored in symlink-ed directories, the URI rewriting * algorithm can fail. To prevent this, provide an array of link paths to * target paths, where the link paths are within the document root. * * Because paths need to be normalized for this to work, use "//" to substitute * the doc root in the link paths (the array keys). E.g.: * <code> * array('//symlink' => '/real/target/path') // unix * array('//static' => 'D:\\staticStorage') // Windows * </code> */
$min_symlinks = array();


/** * If you upload files from Windows to a non-Windows server, Windows may report * incorrect mtimes for the files. This may cause Minify to keep serving stale * cache files when source file changes are made too frequently (e.g. more than * once an hour). * * Immediately after modifying and uploading a file, use the touch command to * update the mtime on the server. If the mtime jumps ahead by a number of hours, * set this variable to that number. If the mtime moves back, this should not be * needed. * * In the Windows SFTP client WinSCP, there's an option that may fix this * issue without changing the variable below. Under login > environment, * select the option "Adjust remote timestamp with DST". * @link http://winscp.net/eng/docs/ui_login_environment#daylight_saving_time */
$min_uploaderHoursBehind = 0;


/** * Path to Minify's lib folder. If you happen to move it, change * this accordingly. */
$min_libPath = dirname(__FILE__) . '/lib';


// try to disable output_compression (may not have an effect)
ini_set('zlib.output_compression', '0');

我们所需要修改的可能就是源文件目录($_min_documentRoot)
和压缩文件缓存目录($_min_cachePath)
准备完成后我们可以找一些比较常用的文件来进行压缩吧。
我的配置
config.php: $_min_documentRoot=根目录/Public

例子1:普通js文件压缩
文件 : jquery.js 大小 (256,592 字节)
文件目录:根目录/Public/js/jquery.js

访问地址: http://localhost/min/?f=js/jquery.js
目标文件大小: (37,793字节)
官网min文件大小: (84,320 字节)
很明显我们压缩的大小比官网的还要写,因此必须要测试是否能够正常使用这个js文件。
测试开始:(简单测试)
【js&css文件压缩】php+minify+nginx 的配置和使用 -1
我们发现$符号能够正确使用jquery的dom操作。同时加载的时候并没有出现错误.因此我们压缩的文件是可以使用的。

例子2:普通css文件压缩
文件: bootstrap.css 大小 (148,206 字节)
文件目录:根目录/Public/css/bootstrap.css
访问地址:http://localhost/min/?f=css/bootstrap.css
目标文件大小:(19,617字节)
说明我们的css文件也成功的压缩了好几倍.

例子3:组合式压缩js文件
如果没有使用g请求,我们也是可以通过f请求做多个文件组合压缩
文件: jquery.js + underscore.js
jquery.js 大小 (256,592 字节)
underscore.js 大小 (54,537 字节)
访问地址:http://localhost/min/?f=js/jquery.js,underscore.js
目标文件大小:(44,660字节)
测试是否能使用该js
【js&css文件压缩】php+minify+nginx 的配置和使用 -1
结果是可以被压缩,并且能够正常使用。

例子4:组合式压缩css文件
同样,我们不使用g请求,通过f请求来对多个css文件进行压缩
文件:bootstrap.css + bootstrap.theme.css
bootstrap.css 大小 (148,206 字节)
bootstrap-theme.css 大小 (23,084 字节)
访问地址:http://localhost/min/?f=css/bootstrap.css,css/bootstrap-theme.css
目标文件大小:(21,822 字节)

例子5:使用g请求进行压缩js文件
我们需要通过编辑groupsConfig.php 文件

<?php
/** * Groups configuration for default Minify implementation * @package Minify */

/** * You may wish to use the Minify URI Builder app to suggest * changes. http://yourdomain/min/builder/ * * See http://code.google.com/p/minify/wiki/CustomSource for other ideas **/

return array(
    // 'js' => array('//js/file1.js', '//js/file2.js'),
    // 'css' => array('//css/file1.css', '//css/file2.css'),
);

在reutrn array(); 里面填写关键的键名和键值,键值则是多个文件路径组合在一起.如果是以/开头或者以//开头则是从制定好的min_documentRoot开始。当然可以使用绝对路径或者../方式向上寻找
文件 jquery.js + underscore.js + backbone.js
jquery.js 大小 (256,592 字节)
underscore.js 大小 (54,537 字节)
backbone.js 大小 (36,200 字节)
访问地址: http://localhost/min/?g=mvc
目标文件大小: (50,951字节)
测试使用情况
【js&css文件压缩】php+minify+nginx 的配置和使用 -1
结果表明压缩后并没有影响js的使用
配置文件如下:

return array(
     'mvc' => array('//js/jquery.js', '//js/underscore.js','//js/backbone.js'),
);

大致的例子已经说完,接下来说一些额外的知识.

  1. 调试模式
    如果我们想要进入调试模式的话,(debug)我们可以在请求的尾部添加一个参数&debug=1。同时在config.php里面将$min_allowDebugFlag设置为true;
    这样我们的响应结果会如下所示:
    【js&css文件压缩】php+minify+nginx 的配置和使用 -1
    内容前面都会有一个行号表示 同时标示来自哪一个文件。
  2. 文件过期
    一般得到的文件的过期时长为30分钟,在config.php中的
    $min_serveOptions[‘maxAge’] 有设置,如果想要将过期长度设置为1年(最大为一年),可以在请求参数中添加&123456 任意数字或者&v 都可行.最好通过数字的不同来确认源文件的修改。

在这里我们主要介绍了minify的使用,如果大家十分喜欢这个插件,可以在上面的开源项目链接中下载这个模块。实际上这个模块还有许多的东西可以说,如果你愿意去了解里面的内容的话。虽然响应的文件都成功的被压缩,但是服务器的处理效率以及浏览器的处理效率并没有进行分析。所以实际上我的任务并没有结束,等再介绍一个新的压缩处理技术后再来进行分析.