Removing unused whitespace with mod_substitute

Unnecessary whitespace comes from many sources: It’s added from developers to have a readable code (required!), it’s added from frameworks (oh well), it’s added from auto-formatting and saving rules of your ide (and 4 tabs may end as 32 spaces), and maybe it’s added from other tools in your development chain. In the development cycle whitespace is important, but when the page is delivered it’s unnecessary. So let’s get rid of it with mod_substitute.

Apaches mod_substitute can “Perform search and replace operations on response bodies”.

It can be used to remove unwanted whitespace from the response:

AddOutputFilterByType SUBSTITUTE text/html
Substitute "s|^[\t ]||f"

This expression, for example, will remove all leading whitespace.

Although removing whitespace can be done with JS and CSS too, for these content type some better tools are available.


  • Every response needs to be changed, which is a waste of ressources compared to an application where no whitespace is sent
  • It’s more effective to remove whitespace at compiletime then at runtime mod_substitute may cause some headaches, as it doesn’t always work as one would expected from a regular expression