Best way to compress HTML, CSS & JS with mod_deflate and mod_gzip disabled

前端 未结 5 2020
轻奢々
轻奢々 2021-02-20 17:48

I have a few sites on a shared host that is running Apache 2. I would like to compress the HTML, CSS and Javascript that is delivered to the browser. The host has disabled mod_d

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-20 18:01

    Sorry about the delay - it's a busy week for me.

    Assumptions:

    • .htaccess is in the same file as compress.php
    • static files to be compressed are in static subdirectory

    I started my solution from setting the following directives in .htaccess:

    RewriteEngine on
    RewriteRule ^static/.+\.(js|ico|gif|jpg|jpeg|png|css|swf)$ compress.php [NC]
    

    It's required that your provider allows you to override mod_rewrite options in .htaccess files. Then the compress.php file itself can look like this:

    You should of course add more mime types to the switch statement. I didn't want to make the solution dependant on the pecl fileinfo extension or any other magical mime type detecting libraries - this is the simplest approach.

    As for securing the script - I do a translation to a real path in the file system so no hacked '../../../etc/passwd' or other shellscript file paths don't go through.

    That's the

    $basedir = realpath( dirname($_SERVER['SCRIPT_FILENAME']) );
    $file = realpath( $basedir . $_SERVER["REQUEST_URI"] );
    

    snippet. Although I'm pretty sure most of the paths that are in other hierarchy than $basedir will get handled by the Apache before they even reach the script.

    Also I check if the resulting path is inside the script's directory tree. Add the headers for cache control as pilif suggested and you should have a working solution to your problem.

提交回复
热议问题