14

All of my .html and .php webpages should be minified. That means I would like to get all HTML-comments and more than one whitespace-character stripped.

Does an Apache-module exist for minification? (Or perhaps another method to automatically add a script directly before the output gets sent to the user?)

(I could add a function like the following, but if an Apache-module or another automatic solution existed, I could not forget to do so.)

<?
function sanitize_output($buffer)
{
    $search = array(
        '/\>[^\S ]+/s', //strip whitespaces after tags, except space
        '/[^\S ]+\</s', //strip whitespaces before tags, except space
        '/(\s)+/s'  // shorten multiple whitespace sequences
        );
    $replace = array(
        '>',
        '<',
        '\\1'
        );
  $buffer = preg_replace($search, $replace, $buffer);
    return $buffer;
}   
?>
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
  • I don't know if this applies to you. But you can let CloudFlare manage your DNS. Then they will minimize your CSS, JavaScript and HTML. But I know that is not as convincing as doing at seeing it on your own system :) – Michael Sep 30 '11 at 05:57
  • 2
    Old question, but for future readers, it is worth noting that if you are on a host with metered bandwidth, while cloudflare will reduce the size of your page presented to the user, it will not reduce the size of the page leaving your server, thus the full size will count against your bandwidth limit. I.e., you can think about this as: Your server-- (_Full Size Page_) --> CloudFlare -- (_Minified Page_) --> User/Client. – Spencer D Nov 24 '16 at 22:28

1 Answers1

29

Try mod_pagespeed which may be of some use to you.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
shrikeh
  • 661
  • 9
  • 12
  • 6
    FYI, for others seeing this, Page Speed will minify HTML, but it is meant to do much more, including inlining and minifying CSS and images (subject to config options). – Paul Draper Jan 06 '14 at 07:04
  • Paul Draper is correct. Pagespeed is an incredibly powerful tool. However, I didn't want to go into great detail in case it clouded how it specifically solved this problem. – shrikeh Feb 09 '14 at 10:25