Nginx 一个高性能的 HTTP 和反向代理服务器

参考资料

1、官方网站:http://nginx.org/

Nginx 介绍

Nginx 是一款轻量级的 Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,其特点是占有内存少,并发能力强,事实上 Nginx 的并发能力在同类型的网页服务器中表现较好。

Nginx 配置文件

1、全局配置:从配置文件开头,到 event 模块开始,主要设置服务器整体运行的配置指令。

worker_processes  1;  //值越大,支持的并发越多。

2、event 模块配置:主要设置服务器与用户网络的连接。

events {
    worker_connections  1024;  //nginx 的最多连接数。
}

3、http 模块配置:这是配置最频繁的部分,代理、缓存、日志定义、第三方的模块配置都在这里。

http {
    include       mime.types;
    default_type  application/octet-stream;
    server {
        listen       80;
        server_name  localhost;
    }
}

Nginx 反向代理

1、添加 host 文件

127.0.0.1 www.feige.com

2、修改配置文件

server {
        listen       80;
        server_name  www.feige.com;

        location ~ /edu/ {  // ~ 代表正则匹配规则
            root   html;
            proxy_pass http://127.0.0.1:8080;
            index  index.html index.htm;
        }
		
	location ~ /void/ {  
            root   html;
            proxy_pass http://127.0.0.1:8081;
            index  index.html index.htm;
        }
}

3、启动访问

Nginx 负载均衡

1、修改配置文件

http {

	upstream backserver {
		// 默认轮询匹配策略
		server 127.0.0.1:8080;
		server 127.0.0.1:8081;
	}

        server {
                listen       80;
                server_name  www.feige.com;

                location / {
                    root   html;
                    proxy_pass http://backserver;
                    index  index.html index.htm;
                }
        }
}

2、访问测试
tomcat1、tomcat2 随机被访问。

3、负载策略
轮询、weight、ip_hash、url_hash、fair(后台响应时间)。

Nginx 动静分离

当客户端访问代理服务器时,首先,加载和显示存放在静态服务器中的静态资源,其次,如果上一步没有匹配对应的资源,我们就认为是动态访问请求,那么就直接访问参与负载均衡的服务器列表中的某一台服务器的动态操作,在实现了动态分离的同时,也参与了服务器的负载均衡。
1、静态资源配置

        location /data/ {
            root   D:/;
            autoindex on;
            index  index.html index.htm;
        }

2、访问测试

Nginx+keepalived 高可用

使用 keepalived 虚拟出一个 IP,绑定上 Nginx 主从服务,如果一台服务挂掉的话,keepalived 会让从服务来处理请求。keepalived 执行我们给定的脚本来判断我们的服务是否挂掉。

Nginx 配置DDOS

1、限制每秒请求次数

limit_req_zone $binary_remote_addr zone=one:10m rate=2r/s;  //每秒2个请求

2、限制连接的数量

limit_conn_zone $binary_remote_addr zone=addr:10m;  //IP对网站打开的连接数不超过10个

3、关闭慢连接

server { 
    client_body_timeout 5s;  //等待时间最大5s
    client_header_timeout 5s;
}

4、设置黑白名单

deny 123.123.123.5;
allow 192.168.1.0/24;

Nginx防盗链

#~表示拦截一切请求,
location ~ .*.(jpg|jpeg|JPG|png|gif|icon)$ {
        #验证域名
        valid_referers blocked http://www.itmayiedu.com www.itmayiedu.com;
        #验证未通过,返回403页面
        if ($invalid_referer) {
            return 403;
        }
        #缓存过期时间30天
        expires   30d;
        #是否记录访问日志
        access_log off;
}
原文地址:https://www.cnblogs.com/feiqiangsheng/p/14486953.html