首页 > 代码库 > Nginx配置缓存,提高网页访问速度

Nginx配置缓存,提高网页访问速度

Nginx自带的缓存,配置起来非常方便,对应静态文件(js, css, swf, png,jpg等等),或者可以缓存的页面。目前在阿里云上买的ECS,运营印象网盘搜索 ,就采用Nginx的缓存。具体配置请看下面代码:

    # proxy缓存临时文件的大小    proxy_temp_file_write_size 256k;    proxy_temp_path ~/nginx/temp;    proxy_cache_path ~/nginx/cache levels=1:2            keys_zone=cache_one:200m inactive=1d max_size=3g;server {        listen       80;         server_name  www.impress.pw;        server_name  ali.impress.pw;        root    impress_root;        index   index.htm;        location / {                                                                                                                                             proxy_cache         cache_one; # 缓存名称            proxy_cache_methods GET HEAD; #尽量不要缓存PUT POST方法            proxy_cache_min_uses 1;            proxy_cache_valid   200 302 10m;            proxy_cache_valid   404 400 1m;             proxy_cache_valid   any 1m; 
proxy_cache_bypass /admin; # 不缓存的方法 proxy_cache_key
"$host:$server_port$uri$is_args$args"; proxy_next_upstream http_502 http_504 error timeout invalid_header; proxy_redirect off; proxy_pass http://impress_server; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # add the Header of expires expires 1d; # File uplaod limits client_max_body_size 2048m; } location /WEB-INF/ { deny all; } location ~ /.*\.(css|js|gif|jpg|jpeg|png|bmp|swf)$ { proxy_cache cache_one; proxy_cache_methods GET HEAD POST; proxy_cache_min_uses 1; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 400 1m; proxy_cache_valid any 1m; proxy_cache_key "$host:$server_port$uri$is_args$args"; # 如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。 proxy_next_upstream http_502 http_504 error timeout invalid_header; proxy_redirect off; proxy_pass http://impress_server; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # the browser cached time expires 10d; } access_log logs/impress_access.log; }

 

注意不要缓存PUT POST等常规认为不缓存的方法

proxy_cache_bypass是指不缓存的URI,多个用空格隔开。

Nginx配置缓存,提高网页访问速度