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;
}   
?>
2
  • 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 :) Commented Sep 30, 2011 at 5: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. Commented Nov 24, 2016 at 22:28

1 Answer 1

29

Try mod_pagespeed which may be of some use to you.

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.