Nginx accelerates website cache and supports html pseudo-static pages

Source: Internet
Author: User
Tags nginx reverse proxy


I. Proxy mode

Proxy mode: cache the specified content when Nginx Reverse proxy is used. The proxy_cache module is used. Many tutorials on the network here will say that this mode can only be used in reverse proxy, as if it cannot be used in the case of only one server. Otherwise, we will try to forward port 80 proxy of the Nginx local machine to port 8080 of the local machine to enable reverse proxy mode in disguise. During this period, you can specify the cached content and continue reading it!

① Download module

The ngx_cache_purge module is used, official address: http://labs.frickle.com/files/, we can pick a new license to download to the server, such as http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz

Cd/usr/local/src
# Download
Wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
# Decompress
Tar zxvf ngx_cache_purge-2.3.tar.gz
② Re-compile
Therefore, run the-V command to check whether Nginx has compiled the module,


[Marsge @ Mars_Server ~] $ Nginx-V
Tengine version: Tengine/2.1.0 (nginx/1.6.2)
Built by gcc 4.4.7 20120313 (Red Hat 4.4.7-11) (GCC)
Tls sni support enabled
Configure arguments: -- user = www -- group = www -- prefix =/usr/local/nginx -- with-http_stub_status_module -- with-http_gzip_static_module -- with-http_concat_module -- add-module = .. /ngx_cache_purge-2.3 -- with-http_image_filter_module -- add-module = .. ngx_slowfs_cache-1.9
[Alert] cocould not open error log file: open () "/usr/local/nginx/logs/error. log" failed (13: Permission denied)
21:38:38 [warn] 30552 #0: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in/usr/local/nginx/conf/nginx. conf: 1
Loaded modules:
Ngx_core_module (static)
Ngx_errlog_module (static)
....
If ngx_cache_purge is not found in the compilation parameters, recompile Nginx and add the compilation parameters:

1
2
# Note that the folder decompressed in the first step is in the same directory as the nginx source code.
-- Add-module = ../ngx_cache_purge-2.3
I am using the Tengine open to Taobao. I can use the dynamic loading module function. For the original version of Nginx, refer to the article shared by Zhang Ge's blog, add the preceding parameters to recompile Nginx:
Detailed operation records of smooth upgrades or new modules under Nginx online service status
③ Add configuration
A. Add cache configuration in the http context:

Http {
# Above
# Cache ##
Proxy_connect_timeout 5;
Proxy_read_timeout 60;
Proxy_send_timeout 5;
Proxy_buffer_size 16 k;
Proxy_buffers 4 64 k;
Proxy_busy_buffers_size 128 k;
Proxy_temp_file_write_size 128 k;
Proxy_temp_path/tmp/nginx_temp_cache1; # temporary cache Directory
Proxy_cache_path/home/wwwroot/cache1 levels = keys_zone = cache_one: 200 m inactive = 30d max_size = 5g; # Set cache storage. You can search for parameters that you do not understand.
# End ##
# Below
....
}

Ps: the directory that appears in the preceding configuration. Save the configuration and use mkdir to create it manually.
B. Modify the original server module of the website as follows:


Server
        {
# Modify the previous listener to listen to local 8080, and keep other configurations unchanged
Listen 127.0.0.1: 8080;
Server_name zhangge.net;
# The following content is omitted...
}
B. The following is a new reverse proxy Server module used to forward requests to the local host 8080. This module implements the reverse proxy mode in disguise:

Server {
Listen 80;
Server_name zhangge.net;
# Cache cleaning module
Location ~ /Purge (/.*){
Allow 127.0.0.1;
Allow 192.168.1.101; # The IP address that allows access to the cache cleaning page
Deny all;
Proxy_cache_purge cache_one $ host $1 $ is_args $ args;
        }
# Cache html pages. You can cache pseudo-static pages. [this is a highlight !]
Location ~ . * \. Html $ {
Proxy_pass http: // 127.0.0.1: 8080;
Proxy_redirect off;
Proxy_set_header Host $ host;
Proxy_cache cache_one;
# Cache for 1 day in 200 or 302 status
Proxy_cache_valid 200 302 1d;
# Cache in 301 status for 2 days
Proxy_cache_valid 301 2d;
Proxy_cache_valid any 1 m;
# Browser expiration time set to 4 hours
Expires 4 h;
# Ignore the header prohibition statement, similar to the forced cache function of CDN.
Proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie ";
# Insert the cache status in the header. The HIT cache is HIT, and the HIT cache is MISS in the dead.
Add_header Nginx-Cache "$ upstream_cache_status ";
        }
# Image cache settings. If The Nginx thumbnail function is not used, this function is not needed and the effect is not obvious.
Location ~ . * \. (Gif | jpg | png | css | jsico )(.*){
Proxy_pass http: // 127.0.0.1: 8080;
Proxy_redirect off;
Proxy_set_header Host $ host;
Proxy_cache cache_one;
Proxy_cache_valid 200 302 30d;
Proxy_cache_valid 301 1d;
Proxy_cache_valid any 1 m;
Expires 30d;
Proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie ";
Add_header Nginx-Cache "$ upstream_cache_status ";
        }
# Directly release dynamic pages without caching
Location ~ . * \. (Php )(.*){
Proxy_pass http: // 127.0.0.1: 8080;
Proxy_set_header Host $ host;
Proxy_set_header X-Real-IP $ remote_addr;
Proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;
        }
# Set the cache blacklist, without caching the specified page, such as wp background or other pages requiring logon status, which are separated by separators
Location ~ ^/(Wp-admin | system) (. *) $ {
Proxy_pass http: // 127.0.0.1: 8080;
Proxy_set_header Host $ host;
Proxy_set_header X-Real-IP $ remote_addr;
Proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;
        }
# Cache pages ending with a slash, similar to the CDN Directory Cache. If there is a problem, please cancel the cache mechanism.
Location ~ /$ {
Proxy_pass http: // 127.0.0.1: 8080;
Proxy_redirect off;
Proxy_set_header Host $ host;
Proxy_cache cache_one;
Proxy_cache_valid 200 302 1d;
Proxy_cache_valid 301 1d;
Proxy_cache_valid any 1 m;
Expires 1 h;
Proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie ";
Add_header Nginx-Cache "$ upstream_cache_status ";
        }
After saving all the data, run nginx-s reload to make the configuration take effect. Now you can access the website's html page and refresh it to see the effect! The loading speed is definitely a qualitative leap! In addition, you can see the Nginx-Cache HIT identifier in the Network status of F12 development mode!
④ Clear cache
It is a little troublesome to clean up the cache. I still don't feel very useful after many times! Many pioneers on the Internet also shared automatic script cleanup or batch cleanup code. However, it is not easy to use.
Let's talk about the cleanup method! In part A's configuration, we have added the purge cache cleanup page. Assume that a url is http: // 192.168.1.1/test.html and is accessed through http: // 192.168.1.1/purge/test.html can clear the cache of the URL (which is usually 404 in my actual test ...).
II. Local mode

In the first proxy mode, we use local forwarding in disguise to implement the Nginx cache function under the reverse proxy, and can cache html pseudo-static pages. From the overall configuration, we can see that it is very close to the CDN cache functions such as Baidu Cloud Acceleration! It is helpful to understand CDN cache!
Now, how can I implement Nginx cache without reverse proxy? It's easy to use the ngx_slowfs_cache module. This is also the mode in which Zhang Ge's blog is using.

① Download module

In this mode, you need to download two cache modules: ngx_cache_purge and ngx_slowfs_cache. The two modules are from a website, download address is still http://labs.frickle.com/files/, select a latest version download can, such:

Http://labs.frickle.com/files/ngx_slowfs_cache-1.9.tar.gz

② Re-compile

Just like the first mode, add two -- add-module to recompile Nginx:

1
-- Add-module = ../ngx_cache_purge-2.3 -- add-module = ../ngx_slowfs_cache-1.9
I will not go into details here. You can refer to the previous articles and blogs for details.
③ Add configuration
I. Add the following configuration in the http context:

Http {
# Above
Slowfs_cache_path/home/wwwroot/cache levels = keys_zone = fastcache: 256 m inactive = 1d max_size = 5g;
Slowfs_temp_path/tmp/nginx_temp_cache 1 2;
# Below
}

Ps: manually create the directories involved in the preceding configuration.

II. Add the following configuration in the server module:


# Add cache cleanup configuration
Location ~ /Purge (/.*){
Allow 127.0.0.1;
Allow 192.168.1.101;
Deny all;
Slowfs_cache_purge fastcache $1;
        }
# Add cache after the thumbnail module of the previous article to cache the generated thumbnails to the disk (for details, refer to the previous article)
Location ~ . * \. (Gif | jpg | jpeg | png | bmp) $ {
Set $ width '';
Set $ height '';
Set $ width $ arg_width;
Set $ height $ arg_height;
If ($ width! = ''){
Add_header Thumbnail "By Nginx ";
            }
If ($ height = ''){
Set $ height '-';
            }
If ($ width = ''){
Set $ width '-';
Set $ height '-';
            }
Image_filter resize $ width $ height;
Image_filter_buffer 5 M;
Image_filter_jpeg_quality 80;
Image_filter_transparency on;
 
# Add cache configuration
Slowfs_cache fastcache;
Slowfs_cache_key $ uri;
Slowfs_cache_valid 1d;
# Insert a cache ID in the header, for example, HIT/MISS from zhangge.net
Add_header X-Cache '$ slowfs_cache_status from $ host ';
Expires max;
}
After saving, run nginx-s reload to reload Nginx. The test found that this mode does not seem to be able to cache html pseudo-static pages. Sorry, if you are interested, you can study it in depth. Maybe I did not test it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.