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

最近沒有更新博客,並不是因爲沒有學習,而是因爲沒有學到一定程度。不過有些比較工具類的知識卻可以拿來小結一下,比如這次所說的文件壓縮。
我們都知道web服務器在處理這樣的靜態文件如圖片,js,css的時候所需要的等待時間是十分長的。因此出現了許多的技術來減少傳送時間。大家都有接觸過xxx.min.js或者xxx.min.css這類的文件.這些文件存儲在服務器上.表示已經被工具進行壓縮了.不過我們也可以通過服務器腳本將請求的css文件或者js文件壓縮後傳送。這就是我們要說的minify模塊。
minify是一個開源的github項目,可以點擊查看項目地址
至於php與nginx的配置可以參考網絡上其他的教程,我們這裏就不多介紹。當然可以使用apache或其他服務器。
關於minify的目錄如下圖所示:
minify-master目錄
這裏我們可以閱讀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文件。
測試開始:(簡單測試)
jquery測試
我們發現$符號能夠正確使用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
結果是可以被壓縮,並且能夠正常使用。

例子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字節)
測試使用情況
mvc組件
結果表明壓縮後並沒有影響js的使用
配置文件如下:

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

大致的例子已經說完,接下來說一些額外的知識.

  1. 調試模式
    如果我們想要進入調試模式的話,(debug)我們可以在請求的尾部添加一個參數&debug=1。同時在config.php裏面將$min_allowDebugFlag設置爲true;
    這樣我們的響應結果會如下所示:
    測試模式
    內容前面都會有一個行號表示 同時標示來自哪一個文件。
  2. 文件過期
    一般得到的文件的過期時長爲30分鐘,在config.php中的
    $min_serveOptions[‘maxAge’] 有設置,如果想要將過期長度設置爲1年(最大爲一年),可以在請求參數中添加&123456 任意數字或者&v 都可行.最好通過數字的不同來確認源文件的修改。

在這裏我們主要介紹了minify的使用,如果大家十分喜歡這個插件,可以在上面的開源項目鏈接中下載這個模塊。實際上這個模塊還有許多的東西可以說,如果你願意去了解裏面的內容的話。雖然響應的文件都成功的被壓縮,但是服務器的處理效率以及瀏覽器的處理效率並沒有進行分析。所以實際上我的任務並沒有結束,等再介紹一個新的壓縮處理技術後再來進行分析.

發佈了31 篇原創文章 · 獲贊 6 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章