VirtualHost模块在交付给客户之前搜索和替换HTML网站代码

I want to replace inside VirtualHost </body> element with:

<!-- Piwik -->
<script type="text/javascript">
  var _paq = _paq || [];
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//stats.mydomain.com/";
    _paq.push(['setTrackerUrl', u+'piwik.php']);
    _paq.push(['setSiteId', '1']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<noscript><p><img src="//stats.mydomain.com/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code --></body>

I need to do this inside VirtualHost section because I can't directly modify website code.

I was thinking about some apache modules like mod_substitute, mod_sed, mod_include.

I need to add this PIWIK statistics code into every page.

Is this good way? Which one of this mods will be best to do this? Or maybe there is another solution?

Below is solution with mod_ext_filter which looks very powerful:

  1. Enable Apache module:

    a2enmod ext_filter
    
  2. Inside Apache configuration file, within VirtualHost section, add filter definition:

    ExtFilterDefine my_html_filter mode=output intype=text/html cmd="/usr/bin/php5 /var/www/data/myfilter.php"
    SetOutputFilter my_html_filter
    
    • ExtFilterDefine - this directive defines filter
    • my_html_filter - it's our filter name
    • mode=output - tells Apache to process the response
    • intype=text/html - specifies the MIME type of documents which should be filtered
    • cmd="/usr/bin/php5 /var/www/data/myfilter.php" - specifies the external command to run
    • SetOutputFilter - this directive activates filter
  3. Content of PHP file /var/www/data/myfilter.php:

    <?php
    
    $stdin = fopen('php://stdin', 'r');
    while($line = fgets($stdin)){
     $line = str_replace('</body>',"
    <!-- Piwik -->
    <script type='text/javascript'>
      var _paq = _paq || [];
      _paq.push(['trackPageView']);
      _paq.push(['enableLinkTracking']);
      (function() {
        var u='//stats.mydomain.com/';
        _paq.push(['setTrackerUrl', u+'piwik.php']);
        _paq.push(['setSiteId', '1']);
        var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
        g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
      })();
    </script>
    <noscript><p><img src='//stats.mydomain.com/piwik.php?idsite=1' style='border:0;' alt='' /></p></noscript>
    <!-- End Piwik Code -->
    </body>", $line);
    
     echo $line;
    }
    fclose( $stdin );
    
    ?>
    
  4. Restart Apache:

    service apache2 restart