Home  >  Article  >  Backend Development  >  How to implement apache php gzip compressed output

How to implement apache php gzip compressed output

WBOY
WBOYOriginal
2016-07-29 09:14:52783browse

1. Introduction to gzip

gzip is the abbreviation of GNU zip. It is a GNU free software file compression program and is often used to represent the file format gzip. The authors of the software are Jean-loup Gailly and Mark Adler. It was first publicly released on October 31, 1992. The version number is 0.1. The current stable version is 1.2.4.

Gzip is mainly used for file compression in Unix systems. We often use files with the suffix .gz in Linux, and they are in GZIP format. Nowadays, it has become a very common data compression format, or file format, used on the Internet. When applying Gzip compression to a plain text file, the effect is very obvious. After GZIP compression, the page size can be reduced to 40% of the original size or even smaller, depending on the content of the file.

 GZIP encoding over HTTP protocol is a technology used to improve the performance of WEB applications. In web development, you can use gzip to compress pages to reduce the website's traffic. However, gzip does not cause a lot of CPU usage. The increase is only a few percentage points, but it can compress the page by more than 30%, which is very cost-effective.

        Using the Gzip module in Apache, we can use the Gzip compression algorithm to compress the web page content published by the Apache server and then transmit it to the client browser. This compression actually reduces the number of bytes transmitted over the network (saving network I/O for transmission). The most obvious benefit is that it can speed up the loading of web pages.

 The benefits of speeding up web page loading are self-evident. In addition to saving traffic and improving the user's browsing experience, another potential benefit is that Gzip has a better relationship with the search engine's crawling tools. For example, Google can crawl web pages faster than ordinary manual crawling by reading gzip files directly. In Google Webmaster Tools you can see that sitemap.xml.gz is submitted directly as a Sitemap. And these benefits are not limited to static content, PHP dynamic pages and other dynamically generated content can be compressed by using the

Apache

compression module, coupled with other performance adjustment mechanisms and corresponding server-side caching rules, this can greatly Improve website performance. Therefore, for PHP programs deployed on Linux servers, we recommend that you enable Gzip Web compression if the server supports it.

2. The process of Web server handling HTTP compression is as follows: 1. After

Web server

receives the HTTP request from the browser, it checks whether the browser supports HTTP compression (Accept-Encoding information ; The latest compressed file of the requested file already exists; 4. If the compressed file of the requested file does not exist, the

Web server

returns the uncompressed requested file to the browser and stores the compressed file of the requested file in the compression buffer directory; 5. If the latest compressed file of the requested file already exists, the compressed file of the requested file will be returned directly;

6. If the requested file is a dynamic file, Web server dynamically compresses the content and returns it to the browser, and the compressed content is not stored in compressed cache directory.

3. Enable the gzip function of

Apache

There are two modules that use the Gzip compression algorithm for compression on Apache: mod_gzip and mod_deflate. To use Gzip web compression, first make sure your server has support for one of these two components. Although using Gzip also requires the support of the client browser, don't worry, most browsers currently support Gzip, such as IE, Mozilla Firefox, Opera, Chrome, etc. By looking at the HTTP header, we can quickly determine whether the client browser used supports gzip compression. If the following information appears in the sent HTTP header, it means that your browser supports the corresponding gzip compression:

The code is as follows: Accept-Encoding: gzip supports mod_gzip Accept-Encoding: deflate supports mod_deflate

Accept-Encoding : gzip, deflate supports both mod_gzip and mod_deflate


View as firebug:

<span>Apache<br /> How to implement php gzip compressed outputAccept-Encoding: gzip,deflate supports both mod_gzip and mod_deflate

If the server has enabled support for the Gzip component, then we can customize it in http.conf or .htaccess. The following is a simple example of .htaccess configuration:

mod_gzip configuration:

code As follows:

# mod_gzip:

mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file. (html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip .*


mod_deflate configuration example:

OpenOpenApache configuration file httpd.conf

#LoadModule deflate_module modules/mod_deflate.so remove the # sign at the beginning

The code is as follows:


# mod_deflate:

DeflateCompressionLevel 6 #Compression rate, 6 is the recommended value.
AddOutputFilterByType DE FLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilter ByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/ atom_xml
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE image/svg+xml


里 The following file MIME types can be added according to your own situation. As for PDF , pictures, music documents and the like are already highly compressed formats. Repeated compression has little effect. On the contrary, it may reduce performance by increasing CPU processing time and browser rendering problems. So there is no need To be compressed again via Gzip. After passing the above settings, check the returned HTTP header. If the following information appears, it means that the returned data has been compressed. That is, the Gzip compression configured in the website program has taken effect.

Content-Encoding: gzip

firebug View:

<img src=

Note:

1) Whether using mod_gzip or mod_deflate, the information returned here is the same. Because they all implement gzip compression.

2) CompressionLevel 9 refers to the level of compression (setting the compression ratio). The value ranges from 1 to 9, with 9 being the highest level. It is understood that this can reduce the size of the transfer by up to 80% (depending on the file content), and can save at least half. CompressionLevel can be set to a value of 6 by default to maintain a balance between processor performance and web page compression quality. It is not recommended to set it too high. If it is set to a high level, although it will have a high compression rate, it will take up more CPU resources.
3) There is no need to compress image formats such as jpg, music files such as mp3, and compressed files such as zip that are already compressed.

4. What are the main differences between mod_gzip and mod_deflate? Which one is better to use?

The first difference is the version of Apache Web server in which they are installed:

Apache The 1.x series does not have built-in web page compression technology, so we use an additional third-party mod_gzip module to perform compression. When Apache 2.x was officially developed, web page compression was taken into consideration, and the mod_deflate module was built-in to replace mod_gzip. Although both use the Gzip compression algorithm, their operating principles are similar.

The second difference is the compression quality:

F MOD_DEFLATE compression speed is slightly faster and MOD_GZIP's compression ratio is slightly higher. Generally, by default, mod_gzip will achieve 4% to 6% more compression than mod_deflate.

So, why use mod_deflate?

                                                                                     .                                          . mod_deflate It is a compression module specially used to ensure the performance of the server, mod_deflate Less resources are required to compress files. This means that on servers with high

traffic, using mod_deflate may load faster than mod_gzip.

do not understand? In short, if your website has less than 1,000 unique visitors per day and you want to speed up the loading of web pages, use mod_gzip. Although it will consume some additional server resources, But it's worth it. If your website has more than 1,000 unique visitors per day and is using a shared virtual host with limited allocated system resources, use mod_deflate will be a better choice.

In addition, starting from Apache

2.0.45, mod_deflate can use DeflateCompressionLevel directive to set the compression level. The value of this directive can be an integer between 1 (fastest compression, lowest compression quality) to 9 (slowest compression, highest compression ratio). Its default value is 6 (compression speed and compression quality). a more balanced value). This simple change makes mod_deflate easily comparable to mod_gzip's compression.

P.S. For virtual spaces that do not have the above two Gzip modules enabled, you can also use PHP's zlib function library (you also need to check whether the server supports it) to compress files. However, this method is more troublesome to use and generally It will consume server resources, so please use it with caution according to the situation.

5. Compression by zlib.output_compression and ob_gzhandler encoding methods

The server does not support mod_gzip and mod_deflate modules. If you want to compress web page content through GZIP, you can consider two methods, turn on

zlib.output_compression or use ob_gzhandler encoding.

.

1) zlib.output_compression is to send data to the client while compressing the web content. 2) ob_gzhandler waits for the web page content to be compressed before sending it. In comparison, the former is more efficient, but it should be noted that the two cannot be used at the same time, you can only choose one, otherwise an error will occur.做 The implementation method of the two is briefly described:

1. ZLib.output_compression Implementation method

By default, zlib.output_compression is closed:

code is as follows:
; Transparent output compression service zlib library

; Valid values ​​for this option are 'off', 'on', or a specific buffer size

; to be used for compression (default is 4KB)

; Note: Resulting chunk size may vary due to nature of compression. PHP

; ; outputs chunks that are few hundreds bytes each as a result of

; compression. If you prefer a larger chunk size for better

; performance, enable output_buffering in addition.
; Note: You need to use zlib.output_handler instead of the standard
; output_handler, or otherwise the output will be corrupted.
; http://php.net/zlib.output-compression
zlib.output_compression = Off
; http://php.net/zlib.output-compression -level
;zlib.output_compression_level = -1






If you want to enable it, edit the php.ini file and add the following content:

The code is as follows:
zlib.output_compression = On
zlib.output_compression_level = 6



You can check the results through the phpinfo() function.
                                                                                    When the values ​​​​of Value and MasterValue are both On, it means that it has taken effect. The PHP page (including pseudo-static page) visited at this time has been GZIP compressed. Through Firebug or The online web page GZIP compression detection tool can detect the compression effect.
2. How to implement ob_gzhandler

If you need to use ob_gzhandler, you need to turn off zlib.output_compression and change the content of the php.ini file to:
zlib.output_compression = Off
zlib.output_compression_level = -1
Implement GZIP compression by inserting relevant code in the PHP file:

The code is as follows:


if (extension_loaded('zlib')) {
if ( !headers_sent() AND isset($_SERVER['HTTP_ACCEPT_ENCODING']) &&
strpos($_SERVER[ 'HTTP_ACCEPT_ENCODING'], 'gzip ') !== FALSE)
                                                                                                                                                                        .
echo $context;
ob_end_flush( );




No matter it is zlib.output_compression or ob_gzhandler, it can only perform GZIP compression on PHP files. Static files such as HTML, CSS, and JS can only be implemented by calling PHP.
The last thing I want to say is that the mainstream browsers now use the HTTP1.1 protocol by default. Basically All support GZIP compression. For IE, if you do not select its menu bar Tools-"Internet Options-"Advanced-"HTTP 1.1 Settings-"Use HTTP 1.1, then you will not feel the pleasure brought by the speed increase after web page compression!

The above introduces the implementation method of apache php gzip compressed output, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn