5.5. nginx配置文件优化二

Nginx Web默认发布静态页面,也可以均衡后端动态页面,用户发起HTTP请求,如果请求为静态页面。 Nginx直接处理并返回,如果请求是动态页面,Nginx收到请求之后会进行判断,转到后端服务器去处理。

Nginx实现负载均衡需要基于upstream模块,同时要设置location proxy_pass转发指令实现。

nginx配置文件详解(这里主要为了达到某个项目需求及作用而配置)

#这里为后端服务器wugk应用集群配置,根据后端实际情况修改即可,test为负载均衡名称,可以任意指定
    #但必须跟vhosts.conf虚拟主机的pass段一致,否则不能转发后端的请求。weight配置权重,在fail_timeout内检查max_fails次数,失败则剔除均衡。(即可理解为负载均衡的安全检查,后面还会演示另种方法)


    upstream test {
        server   127.0.0.1:8080 weight=1 max_fails=2 fail_timeout=30s;
        server   127.0.0.1:8081 weight=1 max_fails=2 fail_timeout=30s;
    }
   #虚拟主机配置
    server {
        #侦听80端口
        listen       80;
        #定义使用www.maxiaotian.com访问,前提为此域名必须解析了此主机IP。
        server_name  www.maxiaotian.com;
        #设定本虚拟主机的访问日志
        access_log  logs/access.log  main;
            root   /data/webapps/maxt;  #定义服务器的默认网站根目录位置
        index index.php index.html index.htm;   #定义首页索引文件的名称
        #默认请求
        location ~ /{
          root   /data/www/maxt;      #定义服务器的默认网站根目录位置
          index index.php index.html index.htm;   #定义首页索引文件的名称
          #以下是一些反向代理的配置.
          proxy_next_upstream http_502 http_504 error timeout invalid_header;
          #如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。
          proxy_redirect off;
          #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_pass  http://tdt_wugk;     #请求转向后端定义的均衡模块
       }

        # 定义错误提示页面
            error_page   500 502 503 504 /50x.html;
            location = /50x.html {
            root   html;
        }
        #配置Nginx动静分离,定义的静态页面直接从Nginx发布目录读取。
        location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$
        {
            root /data/www/maxt;
            #expires定义用户浏览器缓存的时间为3天,如果静态页面不常更新,可以设置更长,这样可以节省带宽和缓解服务器的压力。
            expires      3d;
        }
        #PHP脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
        location ~ \.php$ {
            root /root;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /data/www/wugk$fastcgi_script_name;
            include fastcgi_params;
        }
        #设定查看Nginx状态的地址
        location /NginxStatus {
            stub_status  on;
        }
     }
}

Nginx优化参考文献

https://www.cnblogs.com/xiangsikai/p/9173654.html