Here we will cache gif | jpg | jpeg | png | bmp | swf and configure it as follows:
Open the nginx. conf configuration file and add the following code at the http level.
The code is as follows: |
Copy code |
Proxy_connect_timeout 10; Proxy_read_timeout 180; Proxy_send_timeout 5; Proxy_buffer_size 16 k; Proxy_buffers 4 64 k; Proxy_busy_buffers_size 256 k; Proxy_temp_file_write_size 256 k; Proxy_temp_path/tmp/temp_dir; Proxy_cache_path/home/cache levels = keys_zone = cache_one: 100 m inactive = 1d max_size = 10g; |
Add the following code location at the server level:
The code is as follows: |
Copy code |
Location ~ . * \. (Gif | jpg | jpeg | png | bmp | swf) $ { Expires 15d; } Location ~ . * \. (Js | css )? $ { Expires 1d; } |
If the above settings are set in this way, many friends may not understand the following examples:
If we want to add css and js files to the cache, we only need to modify the location ~ . * \. (Gif | jpg | jpeg | png | bmp | swf) $ to location ~ . * \. (Gif | jpg | png | css | js.
# Set the suffix of the file to be cached.
The code is as follows: |
Copy code |
Location ~ . * \. (Gif | jpg | png | css | js )(.*){ Proxy_pass http: // appserver; Proxy_redirect off; Proxy_set_header Host $ host; Proxy_cache cache_one; Proxy_cache_valid 200 302 24 h; Proxy_cache_valid 301 30d; Proxy_cache_valid any 5 m; Expires 90d; }
|
Note:
1. http settings.
Set temporary directory
Proxy_temp_path/tmp/temp_dir;
Set the cache directory to a second-level Directory, the size of the shared memory area, the inactivity time, and the maximum capacity. The temporary directory must be in the same partition as the cache directory.
Proxy_cache_path/tmp/cache levels = keys_zone = cache_one: 100 m inactive = 1d max_size = 10g;
2. server settings
Set cache shared memory
Proxy_cache cache_one;
Set the http status code to 200,302 cache time, 24 hours for 24 hours
Proxy_cache_valid 200 302 24 h;
Set the expiration time to 90 days.
Expires 90d;
Directly go to the backend server without caching
Proxy_pass http: // 127.0.0.1: 9000;
Of course, we can also use the expires command to configure cache.
The expiration time for controlling images is 30 days. Of course, this time can be set to be longer. Depends on the situation
For example
The code is as follows: |
Copy code |
Location ~ \. (Gif | jpg | jpeg | png | bmp | ico) $ { Expires 30d; } |
Control the maximum cache time of all files in/resource/or/mediatorModule/.
For example
The code is as follows: |
Copy code |
Location ~ /(Resource | mediatorModule )/{ Root/opt/demo; Expires max; } |