matthiasmullie / minify

CSS & JavaScript minifier, in PHP. Removes whitespace, strips comments, combines files (incl. @import statements and small assets in CSS files), and optimizes/shortens a few common programming patterns.
https://matthiasmullie.github.io/minify/
MIT License
1.96k stars 310 forks source link

advice for cache #396

Closed scorninpc closed 2 years ago

scorninpc commented 2 years ago

Hello!

This is more a question/advice for security/fast way to cache than a problem. I see alot people looking for cache, so, sorry if this is a wrong place, but its nice to keep this documented here.

First i'm using gzip, so i done the workaround on htaccess

AddEncoding gzip .jsgz .cssgz
AddType application/x-javascript .jsgz
AddType text/css .cssgz

After that I redirect all css and js from /modules/ directory to my PHP

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^modules/(.*\.(css|js))$ index.php?$1&param=minify

On my PHP, I:

I think my logic is ok, but i'm in doubt if this redirect are ok

The browser target to /modules/css/global.css, i do the processes, save gziped file on /cache/css/526b0d2b64e1f1a76ebc41e457ca584e.cssgz and redirect with header funcion to this new path

On the second time, the browser target to /modules/css/global.css, and I redirect to /cache/css/526b0d2b64e1f1a76ebc41e457ca584e.cssgz with header function with status 302

Do you guys think this is a correct way to cache, or can we get some bether way?

The whole code

if ((isset($_GET['param'])) && ($_GET['param'] == "minify")) {

    // Get css/js filepath
    $_SERVER['QUERY_STRING'] = str_replace("&param=minify", "", $_SERVER['QUERY_STRING']);
    list($name) = explode('?', urldecode($_SERVER['QUERY_STRING']));
    $name = "modules/" . $name;

    // Verify the type
    $type = strtolower(pathinfo($name, PATHINFO_EXTENSION));

    // Verify the cache
    $cache_name = md5($name);
    $cache_file = APPLICATION_PATH . "/../public_html/cache/" . $type . "/" . $cache_name . "." . $type . "gz";
    if(file_exists($cache_file)) {
        header("Location: /cache/" . $type . "/" . $cache_name . "." . $type . "gz", TRUE, 302);
        exit();
    }

    // Minify
    if($type == "css") {
        $minifier = new \MatthiasMullie\Minify\CSS(APPLICATION_PATH . "/../" . PUBLIC_DIR . "/" . $name);
    }
    else {
        $minifier = new \MatthiasMullie\Minify\JS(APPLICATION_PATH . "/../" . PUBLIC_DIR . "/" . $name);
    }
    $minifier->gzip($cache_file);

    header("Location: /cache/" . $type . "/" . $cache_name . "." . $type . "gz", TRUE, 302);
    exit();
}
simondud commented 2 years ago

Hey @scorninpc thanks for sharing; I'm not a cache expert, at a first view having redirects will not help with the speed. Most caching solutions replace the resources URLs in the HTML somehow. I would advise to post your question on stackoverflow or the like, where it could be viewed by folks that have a more hands-on experience with that.