trim

The 'trim' directive removes unnecessary whitespace and comments from HTML responses.

Syntaxtrim on | off;
Defaultoff
Contexthttp, server, location
Arguments1

Description

The 'trim' directive in NGINX is part of the ngx_http_trim_filter module, designed to optimize HTML responses by stripping out excess whitespace (spaces, tabs, newlines) and comments. This filtering process utilizes a state machine to parse through the HTML, ensuring that certain elements—such as those enclosed within <pre>, <textarea>, <script>, and <style> tags—are preserved without modification. In addition to optimizing the HTML for transmission, it aims to maintain the visual integrity of elements where whitespace matters, such as within JavaScript code and CSS styles.

This directive can be enabled or disabled with the syntax trim on; or trim off;, and it also accepts variables, allowing for dynamic configuration based on conditions in NGINX. The default state of the directive is off, meaning that trimming will not occur unless explicitly specified. Importantly, any request with the URL parameter http_trim=off will disable the trimming feature, preserving the unfiltered HTML response for that request. Therefore, it is crucial to configure trimming based on the specific content and needs of your application, carefully considering which MIME types will benefit from this optimization without sacrificing necessary formatting.

Config Example

location / {
    trim on;
    trim_js on;
    trim_css off;
}

Ensure that the 'trim' directive does not compromise elements where whitespace is necessary, such as in certain HTML tags.

Be cautious when using variables in the 'trim' directive as they can lead to unexpected behavior if not correctly configured.

Remember that this directive is overridden if a request contains the parameter 'http_trim=off'.

← Back to all directives