Nginx上可以緩存一些不常更新的靜態資源配置來節約訪問帶寬.
沒緩存前(不走nginx):
沒緩存(走nginx)
配置走nginx緩存
user www www; worker_processes 2; #設置值和CPU核心數一致 error_log /usr/local/webserver/nginx/logs/nginx_error.log crit; #日志位置和日志級別 #access_log /usr/local/webserver/nginx/logs/access.log crit; pid /usr/local/webserver/nginx/nginx.pid; #Specifies the value for maximum file descriptors that can be opened by this process. worker_rlimit_nofile 65535; events { use epoll; worker_connections 65535; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" $http_x_forwarded_for'; #charset gb2312; server_names_hash_bucket_size 128; client_header_buffer_size 32k; large_client_header_buffers 4 32k; client_max_body_size 8m; sendfile on; tcp_nopush on; keepalive_timeout 60; tcp_nodelay on; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; fastcgi_buffer_size 64k; fastcgi_buffers 4 64k; fastcgi_busy_buffers_size 128k; fastcgi_temp_file_write_size 128k; gzip on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_http_version 1.0; gzip_comp_level 2; gzip_types text/plain application/x-javascript text/css application/xml; gzip_vary on; ##cache## proxy_buffer_size 16k; proxy_buffers 4 64k; proxy_busy_buffers_size 128k; proxy_temp_file_write_size 128k; proxy_temp_path /usr/local/webserver/nginx/temp; proxy_cache_path /usr/local/webserver/nginx/cache levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g; ##end## #limit_zone crawler $binary_remote_addr 10m; #下面是server虛擬主機的配置 upstream web_back{ server 127.0.0.1:8080; #並且可以分配權重weight,這樣來配置集群服務器的訪問優先權 } server { listen 8060;#監聽端口 #緩存相應的文件(靜態文件) location ~ .*\.(gif|jpg|jpeg|png|css|js|ico)$ { proxy_pass http://web_back; #如果沒有緩存則通過proxy_pass轉向請求 proxy_redirect off; access_log off;# 關閉日志 proxy_set_header Host $host; proxy_cache cache_one; proxy_cache_valid 200 302 24h; #對不同的HTTP狀態碼設置不同的緩存時間,h小時,d天數 proxy_cache_valid 301 1d; proxy_cache_valid any 1m; expires 30d; add_header wall "cache-file"; } #web 使用 location /cpeducloud { proxy_pass http://localhost:8080/cpeducloud; proxy_redirect http:// https://; sendfile off; proxy_set_header Host $host:$server_port; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_max_temp_file_size 0; #this is the maximum upload size client_max_body_size 0; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 180; proxy_read_timeout 180; proxy_temp_file_write_size 64k; # Required for new HTTP-based CLI proxy_http_version 1.1; } location /download { proxy_pass http://localhost:8080/cpeducloud; proxy_redirect http:// https://; #下載速度限制 #limit_rate_after 10m; limit_rate 5k; } access_log logs/cpeducloud.log main; } }
現在第一次請求會放到緩存中,第二次就直接走的緩存
看請求的時間,節約下來了很多
可以看出效果還是比較明顯的