AlexZ33 / lessions

自己练习的各种demo和课程
12 stars 2 forks source link

Nginx使用记录 #17

Open AlexZ33 opened 5 years ago

AlexZ33 commented 5 years ago

相关文档: nginx api 安装好后 找到Nginx配置文件: /usr/local/etc/nginx/nginx.conf 修改如下 如果电脑文件隐藏,可以按cmd+shift+.显示隐藏文件

安装流程

image

知识结构

模块结构

Nginx 模块图

启动流程

nginx

Nginx Master process和woker process调用流程

Nginx Master process和woker process调用流程

Nginx HTTP Configure Hierarchy

Nginx HTTP Configure Hierarchy

nginx基础用法

安装好后 找到Nginx配置文件: /usr/local/etc/nginx/nginx.conf 修改如下 如果电脑文件隐藏,可以按cmd+shift+.显示隐藏文件

worker_processes  4; # 最好保持和自己电脑的cpu核心数相同

events {
    worker_connections  2048; # 是每个worker进程的最大连接数
}

# Nginx配置文件: /usr/local/etc/nginx/nginx.conf
# Nginx每一条配置语句后面都必须要加 ';'
# 注释用'#'

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    # 负载均衡
    upstream test.mijia.mi.srv {
        server 127.0.0.1:8080; # 项目的实际启动IP和端口,一般vue的项目使用8080
        keepalive 64;
    }
    server{
      listen 80; # 监听端口,如果是webpack项目这里可以写任何端口,例如8090,地址栏的地址就是127.0.0.1:8090/api/
      server_name localhost; # 域名
      # index index.html index.htm index.php; # 若果是通过webpack启动的项目,不需要配置此项
      # root /usr/local/webserver/nginx/html; # 站点目录
      location / {
            # 也可以代理到相应的目录
            # root   /Users/www;
            # index index.htm;

            # 代理到相应的网站
            proxy_pass          https://www.baidu.com; # 如果上边使用upstream,这里的地址需要和upstream保持一致
            # 转发的时候携带cookies
            proxy_set_header    Cookie $http_cookie;
            # 手动添加特殊的cokkies
            # add_header Set-Cookie 'token=xxxxxxxxxxxxx';
            # 可以设置跨域请求头
            add_header          'Access-Control-Allow-Origin' '*';
            add_header          'Access-Control-Allow-Credentials' 'true';
            add_header          'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header          'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-                                   Modified-Since,Cache-Control,Content-Type';
        }
       # 可以根据相应的接口,进行代理
       location ~ ^/api {
            proxy_pass          https://www.baidu.com;
       }
       # 可以写正则,
       location ~ ^/(products|manage)/ {
            proxy_pass          https://www.baidu.com;
       }

       # 错误页面
        error_page   500 502 503 504  /50x/50x.html;
        location = /50x/50x.html {
            root   html;
        }
    }
    include servers/*;
}

切换到nginx目录,在命令行里输入

sudo nginx
# 这样,nginx服务就启动了
# 如果修改相应的配置,需要重启
sudo nginx -s reload
# 关闭服务
nginx -s stop
# 看进程命令
ps aux|grep ‘nginx' 
kill -QUIT 主进程号     :从容停止Nginx
kill -TERM 主进程号     :快速停止Nginx
pkill -9 nginx          :强制停止Nginx

location规则

语法规则: location [=|~|~*|^~] /uri/ { … }

= 开头表示精确匹配
^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。
~ 开头表示区分大小写的正则匹配
~*  开头表示不区分大小写的正则匹配
!~和!~*分别为区分大小写不匹配及不区分大小写不匹配 的正则
/ 通用匹配,任何请求都会匹配到。
多个location配置的情况下匹配顺序为(参考资料而来,还未实际验证,试试就知道了,不必拘泥,仅供参考):
首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求

nginx基本配置与参数说明

user nobody;
#启动进程,通常设置成和cpu的数量相等
worker_processes  1;

#全局错误日志及PID文件
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

#工作模式及连接数上限
events {
    #epoll是多路复用IO(I/O Multiplexing)中的一种方式,
    #仅用于linux2.6以上内核,可以大大提高nginx的性能
    use   epoll; 

    #单个后台worker process进程的最大并发链接数    
    worker_connections  1024;

    # 并发总数是 worker_processes 和 worker_connections 的乘积
    # 即 max_clients = worker_processes * worker_connections
    # 在设置了反向代理的情况下,max_clients = worker_processes * worker_connections / 4  为什么
    # 为什么上面反向代理要除以4,应该说是一个经验值
    # 根据以上条件,正常情况下的Nginx Server可以应付的最大连接数为:4 * 8000 = 32000
    # worker_connections 值的设置跟物理内存大小有关
    # 因为并发受IO约束,max_clients的值须小于系统可以打开的最大文件数
    # 而系统可以打开的最大文件数和内存大小成正比,一般1GB内存的机器上可以打开的文件数大约是10万左右
    # 我们来看看360M内存的VPS可以打开的文件句柄数是多少:
    # $ cat /proc/sys/fs/file-max
    # 输出 34336
    # 32000 < 34336,即并发连接总数小于系统可以打开的文件句柄总数,这样就在操作系统可以承受的范围之内
    # 所以,worker_connections 的值需根据 worker_processes 进程数目和系统可以打开的最大文件总数进行适当地进行设置
    # 使得并发总数小于操作系统可以打开的最大文件数目
    # 其实质也就是根据主机的物理CPU和内存进行配置
    # 当然,理论上的并发总数可能会和实际有所偏差,因为主机还有其他的工作进程需要消耗系统资源。
    # ulimit -SHn 65535

}

http {
    #设定mime类型,类型由mime.type文件定义
    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"';

    access_log  logs/access.log  main;

    #sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,
    #对于普通应用,必须设为 on,
    #如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,
    #以平衡磁盘与网络I/O处理速度,降低系统的uptime.
    sendfile     on;
    #tcp_nopush     on;

    #连接超时时间
    #keepalive_timeout  0;
    keepalive_timeout  65;
    tcp_nodelay     on;

    #开启gzip压缩
    gzip  on;
    gzip_disable "MSIE [1-6].";

    #设定请求缓冲
    client_header_buffer_size    128k;
    large_client_header_buffers  4 128k;

    #设定虚拟主机配置
    server {
        #侦听80端口
        listen    80;
        #定义使用 www.nginx.cn访问
        server_name  www.nginx.cn;

        #定义服务器的默认网站根目录位置
        root html;

        #设定本虚拟主机的访问日志
        access_log  logs/nginx.access.log  main;

        #默认请求
        location / {

            #定义首页索引文件的名称
            index index.php index.html index.htm;   

        }

        # 定义错误提示页面
        error_page   500 502 503 504 /50x.html;
        location = /50x.html {
        }

        #静态文件,nginx自己处理
        location ~ ^/(images|javascript|js|css|flash|media|static)/ {

            #过期30天,静态文件不怎么更新,过期可以设大一点,
            #如果频繁更新,则可以设置得小一点。
            expires 30d;
        }

        #PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
        location ~ .php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include fastcgi_params;
        }

        #禁止访问 .htxxx 文件
            location ~ /.ht {
            deny all;
        }

    }
}
AlexZ33 commented 5 years ago

常用场景

访问限制

经常会遇到希望网站让某些特定用户的群体(比如只让公司内网)访问,或者控制某个uri不让人访问。Nginx配置如下:

 location / {
        deny  192.168.1.100;
        allow 192.168.1.10/200;
        allow 10.110.50.16;
        deny  all;
    }

其实deny和allow是ngx_http_access_module模块(已内置)中的语法。采用的是从上到下匹配方式,匹配到就跳出不再继续匹配。上述配置的意思就是,首先禁止192.168.1.100访问,然后允许192.168.1.10-200 ip段内的访问(排除192.168.1.100),同时允许10.110.50.16这个单独ip的访问,剩下未匹配到的全部禁止访问。实际生产中,经常和ngx_http_geo_module模块(可以更好地管理ip地址表,已内置)配合使用。

跨域

在众多的解决跨域方式中, 都不可避免的都需要服务端进行支持, 使用Nginx可以纯前端解决请求跨域问题。 特别是在前后端分离调试时, 经常需要在本地起前端工程, 接口希望拉取服务端的实际数据而不是本地的mock。 而如果本地程序直接访问远程接口, 肯定会遇到跨域问题。现在前端成熟的做法,一般是把node proxy server集成进来。事实上,用Nginx同样可以解决问题,甚至可以应用于线上。 本地起一个nginx server。server_name是mysite-base.com,比如现在需要请求线上www.kaola.com域下的线上接口 www.kaola.com/getPCBanner… 的数据,当在页面里直接请求,浏览器会报错:

为了绕开浏览器的跨域安全限制,现在需要将请求的域名改成mysite-base.com。同时约定一个url规则来表明代理请求的身份,然后Nginx通过匹配该规则,将请求代理回原来的域。Nginx配置如下:


   #请求跨域,这里约定代理请求url path是以/apis/开头
    location ^~/apis/ {
        # 这里重写了请求,将正则匹配中的第一个()中$1的path,拼接到真正的请求后面,并用break停止后续匹配
        rewrite ^/apis/(.*)$ /$1 break;
        proxy_pass https://www.kaola.com/;
    }  

在页面代码里,把请求url换成http://mysite-base.com/apis/getPCBannerList.html 。这样就可以正常请求到数据。 这样其实是通过nginx,用类似于hack的方式规避掉了浏览器跨域限制,实现了跨域访问。 Reference: Nginx与前端开发

AlexZ33 commented 5 years ago

基本使用

安装好后 找到Nginx配置文件: /usr/local/etc/nginx/nginx.conf 修改如下 如果电脑文件隐藏,可以按cmd+shift+.显示隐藏文件


worker_processes  4; # 最好保持和自己电脑的cpu核心数相同

events {
    worker_connections  2048; # 是每个worker进程的最大连接数
}

# Nginx配置文件: /usr/local/etc/nginx/nginx.conf
# Nginx每一条配置语句后面都必须要加 ';'
# 注释用'#'

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    # 负载均衡
    upstream test.mijia.mi.srv {
        server 127.0.0.1:8080; # 项目的实际启动IP和端口,一般vue的项目使用8080
        keepalive 64;
    }
    server{
      listen 80; # 监听端口,如果是webpack项目这里可以写任何端口,例如8090,地址栏的地址就是127.0.0.1:8090/api/
      server_name localhost; # 域名
      # index index.html index.htm index.php; # 若果是通过webpack启动的项目,不需要配置此项
      # root /usr/local/webserver/nginx/html; # 站点目录
      location / {
            # 也可以代理到相应的目录
            # root   /Users/www;
            # index index.htm;

            # 代理到相应的网站
            proxy_pass          https://www.baidu.com; # 如果上边使用upstream,这里的地址需要和upstream保持一致
            # 转发的时候携带cookies
            proxy_set_header    Cookie $http_cookie;
            # 手动添加特殊的cokkies
            # add_header Set-Cookie 'token=xxxxxxxxxxxxx';
            # 可以设置跨域请求头
            add_header          'Access-Control-Allow-Origin' '*';
            add_header          'Access-Control-Allow-Credentials' 'true';
            add_header          'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header          'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-                                   Modified-Since,Cache-Control,Content-Type';
        }
       # 可以根据相应的接口,进行代理
       location ~ ^/api {
            proxy_pass          https://www.baidu.com;
       }
       # 可以写正则,
       location ~ ^/(products|manage)/ {
            proxy_pass          https://www.baidu.com;
       }

       # 错误页面
        error_page   500 502 503 504  /50x/50x.html;
        location = /50x/50x.html {
            root   html;
        }
    }
    include servers/*;
}

切换到nginx目录,在命令行里输入

sudo nginx
# 这样,nginx服务就启动了
# 如果修改相应的配置,需要重启
sudo nginx -s reload
# 关闭服务
nginx -s stop
# 看进程命令
ps aux|grep ‘nginx' 
kill -QUIT 主进程号     :从容停止Nginx
kill -TERM 主进程号     :快速停止Nginx
pkill -9 nginx          :强制停止Nginx

location规则

语法规则: location [=||*|^~] /uri/ { … }


= 开头表示精确匹配
^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。
~ 开头表示区分大小写的正则匹配
~*  开头表示不区分大小写的正则匹配
!~和!~*分别为区分大小写不匹配及不区分大小写不匹配 的正则
/ 通用匹配,任何请求都会匹配到。
多个location配置的情况下匹配顺序为(参考资料而来,还未实际验证,试试就知道了,不必拘泥,仅供参考):
首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求
AlexZ33 commented 5 years ago

前端开发者必备的nginx知识 centos7.6+nginx+nvm+pm2+nodejs+vuejs初探

AlexZ33 commented 4 years ago

查看配置文件位置

nginx -t

image

image

AlexZ33 commented 4 years ago

Jenkins +nginx 搭建前端构建环境

AlexZ33 commented 4 years ago

nginx配置 map

map指令使用ngx_http_map_module模块提供的。默认情况下,nginx有加载这个模块,除非人为的 --without-http_map_module。 ngx_http_map_module模块可以创建变量,这些变量的值与另外的变量值相关联。允许分类或者同时映射多个值到多个不同值并储存到一个变量中,map指令用来创建变量,但是仅在变量被接受的时候执行视图映射操作,对于处理没有引用变量的请求时,这个模块并没有性能上的缺失。

image

map指令有三个参数:

如果匹配到多个特定的变量,如掩码和正则同时匹配,那么会按照下面的顺序进行选择:

  1. 没有掩码的字符串
  2. 最长的带前缀的字符串,例如: “*.example.com”
  3. 最长的带后缀的字符串,例如:“mail.*”
  4. 按顺序第一个先匹配的正则表达式 (在配置文件中体现的顺序)
  5. 默认值

map_hash_bucket_size 语法: map_hash_bucket_size size; 默认值: map_hash_bucket_size 32|64|128; 配置段: http 指定一个映射表中的变量在哈希表中的最大值,这个值取决于处理器的缓存。

map_hash_max_size 语法: map_hash_max_size size; 默认值: map_hash_max_size 2048; 配置段: http 设置映射表对应的哈希表的最大值。 image image

image

AlexZ33 commented 4 years ago

实例1

#user  nobody; # 用户权限
worker_processes  auto;  # 工作进程的数量(一般等于cpu的总核数或总核数的两倍,例如四核cpu,则总核数为8)
#worker_cpu_affinity auto;

#全局错误日志及PID文件
error_log  logs/error.log;  # 日志输出
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
# 指定pid存放路径
#pid        logs/nginx.pid;

events {
    #epoll是多路复用IO(I/O Multiplexing)中的一种方式,
    #use 设置用于复用客户端线程的轮询方法。如果你使用Linux 2.6+,你应该使用epoll。如果你使用*BSD,你应该使用kqueue。
    use   epoll; # IOCP[window] , kqueue[bsd] , epoll[linux] 

    #单个后台worker process进程的最大并发链接数
    worker_connections  1024;

    #multi_accept 告诉nginx收到一个新连接通知后接受尽可能多的连接。
    multi_accept on;

    # 并发总数是 worker_processes 和 worker_connections 的乘积
    # 即 max_clients = worker_processes * worker_connections
    # 在设置了反向代理的情况下,max_clients = worker_processes * worker_connections / 4  为什么
    # 为什么上面反向代理要除以4,应该说是一个经验值
    # 根据以上条件,正常情况下的Nginx Server可以应付的最大连接数为:4 * 8000 = 32000
    # worker_connections 值的设置跟物理内存大小有关
    # 因为并发受IO约束,max_clients的值须小于系统可以打开的最大文件数
    # 而系统可以打开的最大文件数和内存大小成正比,一般1GB内存的机器上可以打开的文件数大约是10万左右
    # 我们来看看360M内存的VPS可以打开的文件句柄数是多少:
    # $ cat /proc/sys/fs/file-max
    # 输出 34336
    # 32000 < 34336,即并发连接总数小于系统可以打开的文件句柄总数,这样就在操作系统可以承受的范围之内
    # 所以,worker_connections 的值需根据 worker_processes 进程数目和系统可以打开的最大文件总数进行适当地进行设置
    # 使得并发总数小于操作系统可以打开的最大文件数目
    # 其实质也就是根据主机的物理CPU和内存进行配置
    # 当然,理论上的并发总数可能会和实际有所偏差,因为主机还有其他的工作进程需要消耗系统资源。
    # ulimit -SHn 65535
}

http {
    include       mime.types; #设定mime类型,类型由mime.type文件定义
    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"';

    #设置nginx是否将存储访问日志。关闭这个选项可以让读取磁盘IO操作更快
    #access_log  logs/access.log  main;

     #sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,
    #对于普通应用,必须设为 on,
    #如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,
    #以平衡磁盘与网络I/O处理速度,降低系统的uptime.
    # 高效文件传输
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # types_hash_max_size 影响散列表的冲突率。types_hash_max_size越大,就会消耗更多的内存,但散列key的冲突率会降低,检索速度就更快。types_hash_max_size越小,消耗的内存就越小,但散列key的冲突率可能上升。
    types_hash_max_size 2048;

    #连接超时时间
    #keepalive_timeout  0;
    keepalive_timeout  65;

    gzip  on;
    gzip_disable "MSIE [1-6].";
    gzip_comp_level  6;
    gzip_min_length  1000; #置对数据启用压缩的最少字节数。如果一个请求小于1000字节,我们最好不要压缩它,因为压缩这些小的数据会降低处理此请求的所有进程的速度。
    gzip_proxied     expired no-cache no-store private auth;
    gzip_types       text/plain application/x-javascript text/xml text/css application/xml;

    #Buffers:另一个很重要的参数为buffer,如果buffer太小,Nginx会不停的写一些临时文件,这样会导致磁盘不停的去读写,现在我们先了解设置buffer的一些相关参数:
    #client_body_buffer_size:允许客户端请求的最大单个文件字节数
    #client_header_buffer_size:用于设置客户端请求的Header头缓冲区大小,大部分情况1KB大小足够
    #client_max_body_size:设置客户端能够上传的文件大小,默认为1m
    #large_client_header_buffers:该指令用于设置客户端请求的Header头缓冲区大小
    #设定请求缓冲
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    large_client_header_buffers 2 1k;

    map $http_user_agent $outdated {  # 判断浏览器版本
            default                    0;
            "~MSIE [6-9].[0-9]"        1;
            "~MSIE 10.0"               1;
    }

    # weight:轮询权值,默认值为1。
    # down:表示当前的server暂时不参与负载。
    # max_fails:允许请求失败的次数,默认为1。当超过最大次数时,返回 proxy_next_upstream 模块定义的错误。
    # fail_timeout:有两层含义,一是在fail_timeout时间内最多容许max_fails次失败;二是在经历了max_fails次失败以后,30s时间内不分配请求到这台服务器。
    # backup : 备份机器。当其他所有的非 backup 机器出现故障的时候,才会请求backup机器,因此这台机器的压力最轻。
    # max_conns: 限制同时连接到某台后端服务器的连接数,默认为 0。即无限制。
    # proxy_next_upstream : 这个指令属于 http_proxy 模块的,指定后端返回什么样的异常响应

    #负载均衡
    #upstream DataBase {
    #    ip_hash; # 每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
    #    server 10.xx.xx.xx weight=1 max_fails=2 fail_timeout=30s;
    #    server 10.xx.xx.xx;
    #    server 10.xx.xx.xx;
    #}

    server {
        listen       80; #端口号
        server_name  v.fpdiov.com; #域名

        location /api {  #代理API
            proxy_pass   http://api.fpdiov.com:8090;
        #   proxy_set_header Host      $host;
        #   proxy_set_header X-Real-IP $remote_addr; #在web服务器端获得用户的真实ip
        #   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_redirect     off;
            proxy_connect_timeout 600; #nginx跟后端服务器连接超时时间(代理连接超时)
            proxy_read_timeout 600; #连接成功后,后端服务器响应时间(代理接收超时)
            proxy_send_timeout 600; #后端服务器数据回传时间(代理发送超时)
            proxy_buffer_size 32k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小
            proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
            proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)
            proxy_temp_file_write_size 64k; #设定缓存文件夹大小,大于这个值,将从upstream服>务器传
            keepalive_requests 500;
            proxy_http_version 1.1;
            proxy_ignore_client_abort on;
        }

        location ^~ / {
            root /mnt/www/fpd-car-manage-frontend; #启动根目录
            if ($outdated = 1){
                rewrite ^ http://oisbyqrnc.bkt.clouddn.com redirect;  #判断浏览器版本跳转
            }
            index index.html; #默认访问页面
            try_files $uri $uri/ /index.html;
        }
    }

    #server {
    #    listen       80; #侦听80端口
    #    server_name  localhost; #访问域名

        #charset koi8-r; # 字符集

        #access_log  logs/host.access.log  main;

        #location / {
        #    root   html;
        #    index  index.html index.htm;
        #}

        #error_page  404              /404.html; #&emsp;错误页面

        # redirect server error pages to the static page /50x.html
        #
        #error_page   500 502 503 504  /50x.html;
        #location = /50x.html {
        #    root   html;
        #}

        #静态文件,nginx自己处理
        #location ~ ^/(images|javascript|js|css|flash|media|static)/ {

            #过期30天,静态文件不怎么更新,过期可以设大一点,
            #如果频繁更新,则可以设置得小一点。
        #   expires 30d;
        #}

        # 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;
        #}
    #}

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #启用 https, 使用 http/2 协议, nginx 1.9.11 启用 http/2 会有bug, 已在 1.9.12 版本中修复.
    #    listen       443 ssl;
    #    server_name  localhost;
    #     ssl on;
    #    ssl_certificate      cert.pem; #证书路径;
    #    ssl_certificate_key  cert.key; #私钥路径;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5; #指定的套件加密算法
    #    ssl_prefer_server_ciphers  on; # 设置协商加密算法时,优先使用我们服务端的加密套件,而不是客户端浏览器的加密套件。
    #    ssl_session_timeout 60m;  #缓存有效期
    #    ssl_session_cache shared:SSL:10m;  #储存SSL会话的缓存类型和大小
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

配置文件包含了以下一些考虑点:

相关配置解析

nginx配置之proxy_pass

AlexZ33 commented 4 years ago

强制重定向

防止域名被人恶意指向,由于nginx存在默认的空主机头问题,可以通过添加如下配置,将未配置的域名强行重定向,或者return 404

 server {
      listen 80 default;

      server_name _;

      rewrite ^(.*) http://www.mylonly.com permanent;

    }
AlexZ33 commented 4 years ago

try_files

try_files是nginx中http_core核心模块所带的指令,主要是能替代一些rewrite的指令,提高解析效率。官网的文档为 http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

举例说明:

location /images/ { root /opt/html/; try_files $uri $uri/ /images/default.gif; } 比如 请求 127.0.0.1/images/test.gif 会依次查找 1.文件/opt/html/images/test.gif 2.文件夹 /opt/html/images/test.gif/下的index文件 3. 请求127.0.0.1/images/default.gif

其他注意事项 1.try-files 如果不写上 $uri/,当直接访问一个目录路径时,并不会去匹配目录下的索引页 即 访问127.0.0.1/images/ 不会去访问 127.0.0.1/images/index.html

其他用法:

location / { try_files /system/maintenance.html $uri $uri/index.html $uri.html @mongrel; }

location @mongrel { proxy_pass http://mongrel; }

以上中若未找到给定顺序的文件,则将会交给location @mongrel处理(相当于匹配到了@mongrel来匹配)

AlexZ33 commented 4 years ago

检测配置语法错误

修改完配置文件之后,需检测配置语法错误 $nginx -t //测试是否修改成功

AlexZ33 commented 4 years ago

重新加载配置文件

nginx -s reload //重新加载配置文件 (在当前配置文件目录下)

AlexZ33 commented 4 years ago

测试是否请求转发成功

使用postman机或浏览器发出请求,如果出错,查看什么问题,

1)查看nginx日志文件(root权限)

$cd /var/log/nginx

$tail -f error.log

2)没问题后,可以检查自己服务的日志文件(rd权限)

$cd 自己项目的目录文件

$tail -f nohup.out

AlexZ33 commented 4 years ago

常见问题总结

在配置完nginx之后,发现发出请求出现502,查看日志文件,报错: [emerg] 149812#0: io_setup() failed (11: Resource temporarily unavailable) ,通过咨询运维同学,出现该问题的原因是,nginx服务启动了很多次,已经超过了设定的最大限制.解决办法:通过kill掉没用的nginx服务.

注:nginx配置有问题可以咨询运维同学

AlexZ33 commented 4 years ago

线程池

Nginx线程池性能提升9倍(Thread Pools in NGINX Boost Performance 9x!)

AlexZ33 commented 4 years ago

NGINX缓存

NGINX缓存使用官方指南

AlexZ33 commented 4 years ago

虚拟机

在Nginx配置文件中(nginx.conf),一个最简化的虚拟主机配置如下

http 
{
   server
   {
      listen  80 default;
      server_name _*;
       acess_log  logs/default.access.log  combined;
      location / {
        index index.html;
        root /data0/htdocs/htdocs;
      }
   }
}

Nginx 可以配置多种类型的虚拟机

AlexZ33 commented 4 years ago

Nginx日志文件切割

# 将日志文件重命名为/data1/logs/20191021.log
mv /data1/logs/access.log  /data1/logs/20191021.log
# 发送kill -USR1 信号给Nginx的主进程号,让Nginx重新生成一个新的日志文件/ data1/logs/access.log
kill -USR1 Nginx主进程号
AlexZ33 commented 4 years ago

nginx的upstream目前支持的5种方式的分配

1、轮询(默认) 每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。  upstream backserver {  server 192.168.0.14;  server 192.168.0.15;  } 

2、指定权重 指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。  upstream backserver {  server 192.168.0.14 weight=8;  server 192.168.0.15 weight=10;  } 

3、IP绑定 ip_hash 每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。  upstream backserver {  ip_hash;  server 192.168.0.14:88;  server 192.168.0.15:80;  } 

4、fair(第三方) 按后端服务器的响应时间来分配请求,响应时间短的优先分配。  upstream backserver {  server server1;  server server2;  fair;  } 

5、url_hash(第三方) 按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。  upstream backserver {  server squid1:3128;  server squid2:3128;  hash $request_uri;  hash_method crc32;  } 

在需要使用负载均衡的server中增加 

proxy_pass http://backserver/;  upstream backserver{  ip_hash;  server 127.0.0.1:9090 down; (down 表示当前的server暂时不参与负载)  server 127.0.0.1:8080 weight=2; (weight 默认为1.weight越大,负载的权重就越大)  server 127.0.0.1:6060;  server 127.0.0.1:7070 backup; (其它所有的非backup机器down或者忙的时候,请求backup机器)  } 

max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误  fail_timeout:max_fails次失败后,暂停的时间

nginx负载均衡的5种策略及原理

AlexZ33 commented 4 years ago

nginx模块

nginx的模块不像apache的模块一样,nginx的模块是静态编译的,也就是新安装一个模块的话需要重新编译并替换原来的nginx可执行文件。 nginx模块分为3类:

nginx filter模块实践

我们要讲的是filter模块,而filter模块又分为header filter和body filter,从名字上可以看出来header filter处理nginx response的header,body filter处理response的body。由于我们的logid模块需要处理response header去set cookie,所以是一个header filter。

AlexZ33 commented 4 years ago

mac NGinx服务器

AlexZ33 commented 4 years ago

Nginx 502 Bad Gateway问题分析与踩过的坑

AlexZ33 commented 3 years ago

反向代理

image

转发服务

server {
        listen 80;
        access_log /home/work/log/websit.access.log main;
        error_log /home/work/log/websit.error.log;
        server_name localhost;

        location ^~ /public/ {
            alias /home/work/bin/public/;
        }

        location / {
            proxy_pass   http://127.0.0.1:7001/;
            proxy_connect_timeout 600s;
            proxy_read_timeout 600s;
            proxy_send_timeout 600s;
        }

}
AlexZ33 commented 3 years ago

速查


nginx -s reload :修改配置后重新加载生效

nginx -s reopen :重新打开日志文件
nginx -t -c /path/to/nginx.conf 测试nginx配置文件是否正确

关闭nginx:
nginx -s stop :快速停止nginx
quit :完整有序的停止nginx

其他的停止nginx 方式:

ps -ef | grep nginx

kill -QUIT 主进程号 :从容停止Nginx
kill -TERM 主进程号 :快速停止Nginx
pkill -9 nginx :强制停止Nginx

启动nginx:
nginx -c /path/to/nginx.conf

平滑重启nginx:
kill -HUP 主进程号
AlexZ33 commented 3 years ago

配置文件参考

########### 每个指令必须有分号结束。#################
#配置用户或者组,默认为nobody nobody。
#user administrator administrators;
#允许生成的进程数,默认为1
#worker_processes 2;
#指定nginx进程运行文件存放地址
#pid /nginx/pid/nginx.pid;
#制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
error_log log/error.log debug;  

events {
    #设置网路连接序列化,防止惊群现象发生,默认为on
    accept_mutex on;   
    #设置一个进程是否同时接受多个网络连接,默认为off
    multi_accept on;  
     #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    #use epoll;     
    #最大连接数,默认为512
    worker_connections  1024;    
}

http {
    #文件扩展名与文件类型映射表
    include       mime.types;   
    #默认文件类型,默认为text/plain
    default_type  application/octet-stream; 
    #取消服务日志    
    #access_log off; 
    #自定义格式
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; 
    #combined为日志格式的默认值
    access_log log/access.log myFormat;  
    #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
    sendfile on;   
    #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
    sendfile_max_chunk 100k;  
    #连接超时时间,默认为75s,可以在http,server,location块。
    keepalive_timeout 65;  

    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #热备
    }
    error_page 404 https://www.baidu.com; #错误页
    server {
        #单连接请求上限次数。
        keepalive_requests 120;
        #监听端口
        listen       4545;   
        #监听地址       
        server_name  127.0.0.1;  
        #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
        location  ~*^.+$ {       
           #root path;  #根目录
           #index vv.txt;  #设置默认页
           proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表
           deny 127.0.0.1;  #拒绝的ip
           allow 172.18.5.54; #允许的ip           
        } 
    }
}
AlexZ33 commented 3 years ago

前端项目参考

一般前端静态资源使用 nginx 作为访问服务,可以在 git 项目中增加 nginx 配置文件,发布时拷贝到实例的 nginx 配置中。配置文件 website.conf 内容示例:

server {
    listen 8080;

    error_log /home/work/nginx/logs/website-error.log ;
    access_log /home/work/nginx/logs/website-access.log;

    set $html_dir /home/work/bin/;

    root $html_dir;

    # 前端SPA路由配置
    location / {
        alias $html_dir;
        try_files $uri index.html;
    }

    # 设置 html 页面不能缓存,以便客户端能及时更新页面
    location ~ .*\.html$ {
        alias $html_dir/index.html;
        expires 0;
        add_header Cache-Control no-cache;
    }
}
AlexZ33 commented 1 year ago

实例2

# 用户名
user nginx;
# 工作进程数
worker_processes auto;
# 错误日志
error_log /var/log/nginx/error.log;
# 进程管理
pid /run/nginx.pid;

# Load dynamic modules. 加载动态模块
include /usr/share/nginx/modules/*.conf;

# events模块,处理连接的设置
events {
    # 每个进程的最大连接数
    worker_connections 1024;
}

# http服务
http {
    # 日志格式
    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传输文件系统
    # 传统方法:硬盘->内核缓冲区->用户缓冲区->内核socket缓冲区->协议引擎
    # sendfile方法:硬盘->内核缓冲区->内核socket缓存区->协议引擎 
    # sendfile系统调用DMA引擎直接将文件数据从内核缓存区拷贝到内核socket缓冲区,提高了性能
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    # 连接超时时间
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}
AlexZ33 commented 1 year ago

[nginx 添加traceid]()

image