


How to implement apache php gzip compressed output, apachegzip_PHP tutorial
Apache php gzip compression output implementation method, apachegzip
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 become 40% or less of the original size, 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 website traffic. However, gzip does not occupy a lot of CPU. The increase is only a few percentage points, but it can compress pages 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 faster 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 search engine crawlers. 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 be greatly improved 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 processing HTTP compression is as follows:
1. After receiving the HTTP request from the browser, the web server checks whether the browser supports HTTP compression (Accept-Encoding information);
2. If the browser supports HTTP compression, the web server checks the suffix of the requested file;
3. If the requested file is a static file such as HTML, CSS, etc., the web server will check whether the latest compressed file of the requested file already exists in the compression buffer directory;
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, the web server dynamically compresses the content and returns it to the browser. The compressed content is not stored in the compression cache directory.
3. Enable apache’s gzip function
There are two modules on Apache that use the Gzip compression algorithm for compression: 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 with firebug:
Accept-Encoding: gzip,deflate supports both mod_gzip and mod_deflate
If the server enables 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:
The code is as follows:
# mod_gzip: 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.*
< ifModule>
Configuration example of mod_deflate:
Open
will
#LoadModule deflate_module modules/mod_deflate.so
#LoadModule headers_module modules/mod_headers.so
Remove the # sign at the beginning
The code is as follows:
# mod_deflate:
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE application/xhtml xml
AddOutputFilterByType 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
ri
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.
firebug view:
Content-Encoding: gzip
Note:
1) Regardless of 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 have already been 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 the Apache web server in which they are installed:
The Apache 1.x
series does not have built-in web page compression technology, so an additional third-party mod_gzip module is used to perform compression. WhenApache 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:
mod_deflate has a slightly faster compression speed and mod_gzip has a slightly higher compression ratio. Generally, by default, mod_gzip will achieve 4% to 6% more compression than mod_deflate. So, why use mod_deflate?
The third difference is the occupation of server resources:
Generally speaking, mod_gzip consumes a higher amount of server CPU. 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 a high-traffic server, using mod_deflate may load faster than mod_gzip.
Don’t quite 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, but this method is more troublesome to use, and It generally consumes server resources, so please use it with caution according to the situation.
5. zlib.output_compression and ob_gzhandler encoding compression
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. Enable zlib.output_compression or encode through ob_gzhandler .
1) zlib.output_compression compresses the web content and sends data to the client at the same time.
2) ob_gzhandler waits for the web page content to be compressed before sending it. Compared with the former, it is more efficient. However, it should be noted that the two cannot be used at the same time. You can only choose one, otherwise an error will occur.
A brief description of the implementation of the two:
1. zlib.output_compression implementation
By default, zlib.output_compression is off:
The code is as follows:; Transparent output compression using the 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 need to edit the php.ini file to open it, add the following content:
zlib.output_compression = On
zlib.output_compression_level = 6
You can check the result through the phpinfo() function.
When the Local of zlib.output_compression
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. Implementation of 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
By inserting in the PHP file Related code implements GZIP compression P compression:
if (extension_loaded('zlib')) {
if ( !headers_sent() AND isset($_SERVER['HTTP_ACCEPT_ENCODING']) &&
strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'g zip' ) == False)
// Pages are not output and the browser can accept the page of gzip
{
OB_START ('OB_GZHANDLER'); Compressed content
echo $context;
ob_end_flush();
No matter it is zlib.output_compression or ob_gzhandler, it can only perform GZIP compression on PHP files. For static files such as HTML, CSS, JS etc. Files 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.
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!
http://www.bkjia.com/PHPjc/1056839.html

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

To set up a CGI directory in Apache, you need to perform the following steps: Create a CGI directory such as "cgi-bin", and grant Apache write permissions. Add the "ScriptAlias" directive block in the Apache configuration file to map the CGI directory to the "/cgi-bin" URL. Restart Apache.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

When the Apache 80 port is occupied, the solution is as follows: find out the process that occupies the port and close it. Check the firewall settings to make sure Apache is not blocked. If the above method does not work, please reconfigure Apache to use a different port. Restart the Apache service.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.
