目录
本文详细记录了nginx实现缓存的配置步骤,nginx是一个非常优秀的web服务,同时还具有正向代理,反向代理,负载均衡以及缓存等功能。
操作系统 | 配置 | 主机名 | IP |
---|---|---|---|
CentOS7.3.1611 | 2C4G | nginx | 192.168.207.131 |
CentOS7.3.1611 | 2C4G | httpd | 192.168.207.165 |
CentOS7.3.1611 | 2C4G | client | 192.168.207.166 |
- systemctl stop firewalld
- systemctl disable firewalld
- setenforce 0
- sed -i "s/^SELINUX=.*/SELINUX=disabled/g" /etc/selinux/config
- hostnamectl set-hostname nginx
- hostnamectl set-hostname httpd
- hostnamectl set-hostname client
- yum -y install httpd
- echo httpd > /var/www/html/index.html
- systemctl start httpd
- cat > /etc/yum.repos.d/nginx.repo << 'EOF'
- [nginx]
- name=nginx repo
- baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
- gpgcheck=0
- enabled=1
- EOF
-
- yum -y install nginx
- # 在/etc/nginx/nginx.conf的http段中添加
- upstream node {
- server 192.168.207.166:80;
- }
- proxy_cache_path /cache levels=1:2 keys_zone=cache:10m max_size=10g inactive=60m use_temp_path=off;
-
- # 在/etc/nginx/conf.d/default.conf的server段下的 location / 中添加
- location / {
- root /usr/share/nginx/html;
- index index.html index.htm;
- proxy_pass http://node;
- proxy_cache cache;
- proxy_cache_valid 200 304 12h;
- proxy_cache_valid any 10m;
- add_header Nginx-Cache "$upstream_cache_status";
- proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
- }
配置详解
- proxy_cache_path /cache levels=1:2 keys_zone=cache:10m max_size=10g inactive=60m use_temp_path=off;
- #proxy_cache //存放缓存临时文件
- #levels //按照两层目录分级
- #keys_zone //开辟空间名,10m:开辟空间大小,1m可存放8000key
- #max_size //控制最大大小,超过后Nginx会启用淘汰规则
- #inactive //60分钟没有被访问缓存会被清理
- #use_temp_path //临时文件,会影响性能,建议关闭
-
- proxy_cache cache;
- proxy_cache_valid 200 304 12h;
- proxy_cache_valid any 10m;
- add_header Nginx-Cache "$upstream_cache_status";
- proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
- #proxy_cache //开启缓存
- #proxy_cache_valid //状态码200|304的过期为12h,其余状态码10分钟过期
- #proxy_cache_key //缓存key
- #add_header //增加头信息,观察客户端respoce是否命中
- #proxy_next_upstream //出现502-504或错误,会跳过此台服务器访问下一台服务器
- nginx -t
-
- systemctl start nginx
- if ($request_uri ~ ^/(static|login|register|password)) {
- set $cookie_nocache 1;
- }
- location / {
- proxy_pass http://node;
- proxy_cache cache;
- proxy_cache_valid 200 304 12h;
- proxy_cache_valid any 10m;
- add_header Nginx-Cache "$upstream_cache_status";
- proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
- proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
- proxy_no_cache $http_pargma $http_authorization;
- }
- curl 192.168.207.131
- httpd
- curl 192.168.207.131
- httpd