花样百米自由泳研究协会

我们除了上班对啥都感兴趣

努力不一定能成功,但不努力一定很轻松╮( ̄▽  ̄)╭
  menu
6 文章
0 浏览
0 当前访客
ღゝ◡╹)ノ❤️

nginx

srchttpcdn2.lmonkey.comuploadimg0a60e90ef09a5caca4a302a9550d6deb.jpegreferhttpcdn2.lmonkey.jpeg

nginx介绍

nginx当下主流webserver之一,主要应用于转发和反向代理

nginx配置文件模版实例

user  nobody;				#线程用户
worker_processes  1;			#工作进程数

error_log  /var/log/nginx/error.log;	#错误日志路径
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
events {
    worker_connections  1024;		#单个工作进程可以允许同时建立外部连接的数量
}


http {					#http块
    include       mime.types;		#引入的配置文件
    #include       demo.conf;
    include       solo.conf;
    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"';   ##日志格式化

    access_log  /var/log/nginx/access.log   main;   #日志路径

    #sendfile        on;			#高性能系统接口反响代理时无意义
    #tcp_nopush     on;				#sendfeile协作配置

    #keepalive_timeout  0;
    keepalive_timeout  60;			#连接断开后存留的生命周期

    #gzip  on;					#压缩

    server {					#server块
#        listen       80;			#监听端口
#        server_name  localhost;		#域名

#        location / {				#location块
#            root   html;			#家目录
#            index  index.html index.htm;	#识别文件类型
#        }

        error_page  404  /404.html;		#错误页


        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;#错误页
        location = /50x.html {
            proxy_pass  http://www.baidu.com;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;	#反响代理转发地址
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

nginx实用参数

location的匹配

分为有修饰符和无修饰符两种

无修饰符
server {   

 server_name website.com;  

location / { 		#完全匹配

   […]  

}

}
有修饰符

按修饰符类型以正则匹配

「=」 修饰符:要求路径完全匹配**
server {   

 server_name website.com;  

location = /abcd { 		#只有完全匹配abcd才会被匹配进入

   […]  

}

}
「~」修饰符:区分大小写的正则匹配
server { 

   server_name website.com;   

 location ~ ^/abcd$ { 		#这个正则表达式表示字符串必须以/开始,以$结束,中间必须是abcd切大小写敏感

   […]  

}

}
「~*」不区分大小写的正则匹配
server {   

 server_name website.com;  

  location ~* ^/abcd$ {  		#这个正则表达式表示字符串必须以/开始,以$结束,中间必须是abcd切大小写不敏感

  […]  

  }

}
「^~」修饰符:前缀匹配(非正则)
server {   

 server_name website.com;  

  location ^~/abcd/ {  		#匹配到这个表达式后立即停止后续的正则搜索

  […]  

  }

}

代理转发

http代理转发

proxy_pass   http:127.0.0.1:8080;

ajp代理转发(需ajp模块支持)

ajp_pass 127.0.0.x:8009; 

http跳转https

  1. 重写url

    rewrite ^ https://$http_host$request_uri? redirect;   #定义在80server块的location块中直接转发
    

    permanent为永久重定向状态码为301,redirect则为临时重定向状态码为302,仅影响seo

  2. 指定状态码转发

拦截ip访问转为域名

server {

        listen 80 default;
        listen 443 default_server;

        return 403;	#此处纯粹拦截有些浪费流量蚊子腿再小也是肉,下面进阶一下将其以https安全访问的形式引入我们的域名
}


server {

        listen 80 default;
        listen 443 default_server;

        ssl_certificate /usr/local/nginx/ssl/pem;  # managed by Certbot
        ssl_certificate_key /usr/local/nginx/ssl/key; # managed by Certbot
        ssl_session_timeout 5m;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;

        server_name _;
        rewrite ^ http://domainname$request_uri? redirect;

}

禁止非GET|HEAD|POST方式的抓取 

if ($request_method !~ ^(GET|HEAD|POST)$) { 
    return 403; 	#直接返回403
}

gzip压缩

GZIP是若干文件压缩程序的简称,通常指GNU计划的实现,此处的GZIP代表的就是GUN ZIP,这也是HTTP1.1协议定义的两种压缩方法中最常用的一种压缩方法,客户端浏览器大都支持这种压缩格式。

gzip on;  			#开启压缩
        gzip_min_length 1k;   	#设置压缩最小单位,小于不压缩
    #gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    gzip_comp_level 4;  	#压缩比取值1~9权衡性能消耗推荐4
    gzip_buffers 4 16k;  	#申请内存,前段为倍数后段为单位;示例中为64k
    gzip_http_version 1.1;	#识别版本进行压缩,就是说对HTTP/1.1协议的请求才会进行gzip压缩
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;  #压缩内容

负载均衡

负载均衡之所以单拿出来说是因为涉及的东西比较多

Nginx支持的负载均衡调度算法方式如下:

  • weight轮询(默认):接收到的请求按照顺序逐一分配到不同的后端服务器,即使在使用过程中,某一台后端服务器宕机,Nginx会自动将该服务器剔除出队列,请求受理情况不会受到任何影响。 这种方式下,可以给不同的后端服务器设置一个权重值(weight),用于调整不同的服务器上请求的分配率;权重数据越大,被分配到请求的几率越大;该权重值,主要是针对实际工作环境中不同的后端服务器硬件配置进行调整的。
  • ip_hash:每个请求按照发起客户端的ip的hash结果进行匹配,这样的算法下一个固定ip地址的客户端总会访问到同一个后端服务器,这也在一定程度上解决了集群部署环境下session共享的问题。
  • fair:智能调整调度算法,动态的根据后端服务器的请求处理到响应的时间进行均衡分配,响应时间短处理效率高的服务器分配到请求的概率高,响应时间长处理效率低的服务器分配到的请求少;结合了前两者的优点的一种调度算法。但是需要注意的是Nginx默认不支持fair算法,如果要使用这种调度算法,请安装upstream_fair模块。
  • url_hash:按照访问的url的hash结果分配请求,每个请求的url会指向后端固定的某个服务器,可以在nginx作为静态服务器的情况下提高缓存效率。同样要注意Nginx默认不支持这种调度算法,要使用的话需要安装nginx的hash软件包。

| 参数 | 描述 |
| - | - |
| fail_timeout | 与max_fails结合使用。 |
| max_fails | 设置在fail_timeout参数设置的时间内最大失败次数,如果在这个时间内,所有针对该服务器的请求都失败了,那么认为该服务器会被认为是停机了。 |
| fail_time | 服务器会被认为停机的时间长度,默认为10s。 |
| backup | 标记该服务器为备用服务器。当主服务器停止时,请求会被发送到它这里。 |
| down | 标记服务器永久停机了。 |

示例:

upstream lb {
    ip_hash;				#ip绑定达成会话保持
    server localhost:8001 weight=2;	#此端口权重为2
    server localhost:8002;
    server localhost:8003;
    server localhost:8004 max_fails=3 fail_timeout=10s;   #此端口在10妙内若有三次为超时则视为不可用后续不在转发
    server localhost:8004 backup;	#备用端口即有可用端口时不向内转发
}

server{
	listen 80;
	server_name domain;

	location /{
	proxy_pass lb;
	}
}

常见安全类

add_header X-Frame-Options SAMEORIGIN; # 只允许本站用 frame 来嵌套
add_header X-Content-Type-Options nosniff; # 禁止嗅探文件类型
add_header X-XSS-Protection "1; mode=block"; # # XSS 保护


###frame 同源策略
add_header X-Frame-Options SAMEORIGIN;
###CSP防护
add_header  Content-Security-Policy  "default-src 'self'; script-src 'self' 'unsafe-inline';font-src 'self' data:; img-src 'self'  data: 'unsafe-inline' https:; style-src 'self' 'unsafe-inline';frame-ancestors 'self'; frame-src 'self';connect-src https:";
###开启XSS防护
add_header X-Xss-Protection "1";
###资源解析
add_header X-Content-Type-Options nosniff;
###HSTS防护
add_header Strict-Transport-Security "max-age=172800; includeSubDomains";
ch z#上传文件大小上限
client_max_body_size 200M;

标题:nginx
作者:constantinejc
地址:https://www.missyou.info/articles/2021/03/25/1616654985461.html