zoukankan      html  css  js  c++  java
  • Nginx入门

    二进制安装nginx

    准备编译环境

    yum install pcre-devel openssl-devel zlib-devel gcc -y
    useradd -r -s /sbin/nologin nginx
    mkdir -p /data/nginx # 预安装路径
    

    编译

     tar xvf nginx-1.18.0.tar.gz -C /usr/local/src/
     cd /usr/local/src/nginx-1.18.0
     ./configure --prefix=/data/nginx --user=nginx --group=nginx 
     --with-http_ssl_module 
     --with-http_v2_module 
     --with-http_realip_module 
     --with-http_stub_status_module 
     --with-http_gzip_static_module 
     --with-pcre 
     --with-stream 
     --with-stream_ssl_module 
     --with-stream_realip_module 
     
     make -j 4 && make install
     ln -s /data/nginx/sbin/nginx /usr/sbin/ # 软链接
    

    使用systemd启动方式

    vim /usr/lib/systemd/system/nginx.service
    
    [Unit]
    Description=The nginx HTTP and reverse proxy server
    After=network.target remote-fs.target nss-lookup.target
    
    [Service]
    Type=forking
    PIDFile=/data/nginx/logs/nginx.pid
    # Nginx will fail to start if /run/nginx.pid already exists but has the wrong
    # SELinux context. This might happen when running `nginx -t` from the cmdline.
    # https://bugzilla.redhat.com/show_bug.cgi?id=1268621
    ExecStartPre=/usr/bin/rm -f /data/nginx/logs/nginx.pid
    ExecStartPre=/usr/sbin/nginx -t
    ExecStart=/usr/sbin/nginx -c /data/nginx/conf/nginx.conf
    ExecReload=/bin/kill -s HUP $MAINPID
    KillSignal=SIGQUIT
    TimeoutStopSec=5
    KillMode=process
    PrivateTmp=true
    
    [Install]
    WantedBy=multi-user.target
    

    启动

    systemctl restart nginx
    systemctl enable nginx
    
    nginx -V 查看编译参数
    nginx -s reload 热加载配置
    nginx -t 测试conf文件语法有没有错误
    nginx 启动nginx服务
    

    nginx性能优化

    nginx.conf

    全局配置

    worker_processes  auto; # 启动进程数,auto当前多少cpu就启动多少个
    
    # ps -eo pid,args,psr查看进程启动在哪个cpu上
    worker_cpu_affinity 0001 0010 0100 1000; # cpu亲和性
    
    # 查看进程优先级ps -le |grep nginx,-20-19越大优先级越低
    worker_priority -20; # 修改进程优先级
    
    #echo ulimit -n 65535 >>/etc/profile && source /etc/profile
    worker_rlimt_nofile 65535; work进程能打开的文件数量上限,设置于ulimt -n的值保持一致,如65535.
    
    

    事件驱动配置

    events {
        worker_connections  10240; # 每个work进程能打开的最大并发连接数,如10240,总最大并发数worker_processes*worker_connections
        use method; # 并发连接请求的处理方式,默认自动选择最优方法, 如use epoll;
        accept_mutex on|off; # 处理新的连接请求方法,on指由各个worker轮流处理新的请求,off指每个新请求的到达都会通知所有worker进程,但只有一共进程获得连接,造成惊群,影响性能,默认值为off,优化为on
        multi_accept on|off; # 默认为off,默认为一个worker进程只能一次接收一个新的网络连接,on表示每个worker可以同时接收所有新的网络连接
    }
    

    调试和定位问题-全局配置

    daemon on|off; 默认on守护进程方式,off前台运行用于调试或者docker环境
    master_process on|off; 是否以master/worker模型运行nginx,默认on,当指定off将不启动worker
    error_log logs/error.log [level]; 错误日志文件及其级别; 出于调试需要,可设定为debug; 但debug需要编译时使用 --with-debug 才能生效
    	logs/error.log 记录到文件中
    	stderr 发生到标准错误,运行为docker时stderr可以采集错误日志
    	syslog: server-address[,parameter=values] 发生到syslog
    	memory:size 内存
    	[level]日志级别: debug/info/notice/warn/error/crit/alter/emerg
    
    

    nginx模块module

    官网地址http://nginx.org/en/docs/

    ngx_http_core_module

    http://nginx.org/en/docs/http/ngx_http_core_module.html

    在响应报文中将指定的文件扩展名映射至MIME对应的类型

    include mime.types;
    default_type application/octet-stream; 除了上面指定的类型外,就为默认的MIME类型,浏览器一般会提示下载
    types {
        text/html                                        html htm shtml;
        text/css                                         css;
        text/xml                                         xml;
        image/gif                                        gif;
        image/jpeg                                       jpeg jpg;
    }
    

    MIME参考文档:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types

    tcp_nodelay on|off; 在keepalived模式下的连接是否启用TCP_NODELAY选项,既Nagle算法当为off时,延迟发送,每发生一次包就需要确定ACK,才发送下一个包。默认为On时,不延迟发送,多个包才确认一次,用于http,server,location
    
    tcp_nopush on|off; 在开启sendfile,on时合并响应头和数据体在一个包中一起发送
    
    sendfile on|off; 是否启用sendfile,在内核中封装报文直接发送,默认off
    
    charset charset|off; 是否在响应报文中的Content-Type显示指定的字符集,默认off不显示
    
    server_tokens on|off|build|string; 是否在响应报文的Server首部显示nginx版本。生产环境一般off,隐藏nginx版本号
    
    server {
            listen  port|unix:/PATH/TO/SOCKET_FILE|ssl|http2|spdy|backlog=number|rcvbuf=size|sndbuf=size default_server; 
    }
            #default_server设定为默认虚拟主机,无法匹配虚拟主机时使用
            #ssl 限制仅能通过ssl连接提供服务
            #backlog=number 超过并发连接数后,新请求进入后援队列的长度
            #rcvbuf=size 接收缓冲区大小
            #sndbuf=size 发送缓冲区大小
     注意:
     listen port; 监听不同端口
     listen ip:port; 监听ip+端口
     server_name fqdn; 监听不同主机名
    
     server_name hostname;
     	虚拟主机的主机名称后可跟多个由空白字符串分隔的字符串
     	支持*通配任意长度的任意字符server_name *.xx.com www.xx.*
     	支持~起始的字符做正则表达式模式匹配,性能原因不要用 server_name ~^wwwd+.xx.com$
     	匹配优先级:精确匹配>左侧*通配符>右侧*通配符>正则表达式>default_server
    
     location
     	= 对url做精确匹配 
     	^~ 对url最左边做匹配检查,不区大小写
     	~ 对url做正则匹配,区分大小写
     	~* 对url做正则匹配,不区分大小写
     	不带符合 匹配起始于此开头的所有url
     	 转义符,可将.*?等转义为普通符号
     	匹配优先级:"=" > "^~" > "~"/"~*" > "不带符合"
    
     alias path; 路径别名,文档映射的另一种机制;仅能用于location中
     location /test {
     	alias /web/#访问的是路径/web/index.html
     }
     location /test {
     	root /web/ #访问的是路径/web/test/index.html 多出/test
     }
     location中使用root指令和alias指令的意义不同
     	root: 给定的路径对应于location中的/url 左侧的/
     	alias: 给定的路径对应于location中/url 的完整路径
    
    error_page code url; 定义错误页,以指定的响应状态码进行响应,可用位置:http/server/location/if in location
    error_page 404 /404.html;
    location = /40x.html{
    }
    error_page 404 =200 /404.html 
    
    error_page 500 502 503 504 /50x.html
    location = /50x.html{
    }
    
    try_files file uri;
    try_files file =code;
    
    按顺序检查文件是否存在,返回第一个找到的文件或者文件夹(结尾加斜线表示为文件夹),如果所有文件或文件夹都找不到,i进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部uri的指向,最后一个参数回退url且必须存在,否则会出现内部500错误
    location /img/ {
    	try_files $uri /img/default.jpg; # 说明/img/default.jpg 为uri
    } 
    location / {
    	try_files $uri $uri/index.html $uri.html =404;
    }
    
    定义客户端请求相关配置:
    keepalive_timeout timeout [header_timeout]; 设定保持连接超时时长,0表示禁止长连接,默认为75s 
    keepalive_timeout 60 60; 在响应头显示此首部字段
    
    keepalive_requests number; 在一次长连接上所允许请求的资源的最大数量,默认为100
    
    keepalive_disable none|browser; 对哪种浏览器禁止长连接
    
    send_timeout time; 向客户端发送响应报文的超时时长,此处是指两边写操作之间的间隔时长,而非整个响应过程的传输时长
    
    client_max_body_size size; 指定请求报文实体最大值,设为0则不限制。默认1m超过报413错误
    
    client_body_buffer_size size; 用于接收每个客户端请求报文的body部分的缓冲区大小; 默认为16k;超出此大小,其将被暂存到磁盘上的由下面client_body_temp_path指令所定义的位置
    
    client_body_temp_path path [level1][level2][level3]; 设定存储客户端请求报文的body部分的临时存储路径及子目录结构和数量目录名为16进制的数字;用hash之后的值从后往前截取第1、2、3级作为文件名client_body_temp_path /var/tmp/client_body 1 2 2
    1 1级目录占1位16进制,既2^4=16个目录0-f
    2 2级目录占2位16进制,既2^8=256个目录 00-ff
    2 3级目录占2位16进制,既2^8=256个目录 00-ff
    
    上传文件服务器配置生产案例:
    location /upload {
    	client_max_body_size 300m;
    	client_body_buffer_size 2048k;
    	client_body_temp_path /var/nginx/temp 1 2 2;
    }
    
    文件操作优化的配置:
    aio on|off|threads[=pool]; 是否启用aio功能,默认off
    directio size|off; 当文件大于等于给定大小时,直接同步写磁盘,而不是写缓存,默认off
    例如:
    location /video {
    	sendfile on;
    	aio on;
    	directio 8m;
    }
    
    对客户端进行限制的相关配置:
    limit_rate rate; 限制响应给客户端的传输速率,单位是bytes/second。默认值0表示无限制
    limit_except method method 仅用于location限制客户端使用指定的请求方法:  GET, HEAD, POST, PUT, DELETE,MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, or PATCH
    
    limit_except GET {
        allow 192.168.1.0/24;
        deny  all;
    }
    除了GET和HEAD之外其它方法仅允许192.168.1.0/24网段主机使用
    
    open_file_cache off;
    open_file_cache max=N [inactive=time];
    	max=N:可缓存的缓存项上限;达到上限后会使用LRU算法实现管理
    	inactive=time:缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于open_file_cache_min_uses指令所指定的缓存项即为非活动项,将被删除
    	nginx可以缓存以下三种信息:
    	1、文件元数据:文件的描述符、文件大小和最近一次修改时间
    	2、打开的目录结构
    	3、没有找到的或者没有权限访问的文件的相关信息
    
    open_file_cache_errors on|off; 是否缓存查找时发生错误的文件类信息,默认值off;
    open_file_cache_min_uses number;	open_file_cache指令的inactive参数指定的时长内,至少被命中此处指定的次数方可被归类为活动项,默认值为1;
    open_file_cache_valid time; 缓存项有效性的检查频率,默认值为60s
    

    ngx_http_index_module

    index file; 指定默认网页文件
    

    ngx_http_access_module

    可实现基于ip的访问控制功能,用于http、server、location、limit_except。自上而下检查,一旦匹配,将生效,条件严格的置前

    allow address|CIDR|unix:|all; 允许

    deny address|CIDR|unix:|all; 拒绝

    例如:先允许小部分,再拒绝大部分

    location /about {
    	root /data/nginx/html/pc;
    	index index.html;
    	deny 192.168.1.1;
    	allow 192.168.1.0/24;
    	allow 10.1.0.0/16;
    	allow 2001:000d::/32;
    	deny all;
    
    }
    

    ngx_http_auth_basic_module

    实现基于用户的访问控制,使用basic机制进行用户认证

    auth_basic string|off;
    auth_basic_user_file file;
    
    location /admin/ {
    	auth_basic "admin admin";
    	auth_basic_user_file /etc/nginx/.nginxuser
    }
    
    用户口令文件:
    1、明文文本:格式name:password:comment
    2、加密文本:由htpasswd命令实现httpd-tools所提供
    

    ngx_http_stub_status_module

    用于输出nginx的基本状态信息

    Active connections: 291
    server accepts handled requests       #下面分别对应accepts handled requests
    		16630948 16630948 31070465
    Reading: 6 Writing: 179 Waiting: 106
    
    Active connections: 当前状态,活动状态的连接数
    accepts: 已经接受的客户端请求总数
    handled: 已处理完成的客户端请求总数,一般和accepts相同,除非拒绝
    requests: 客户端发来的总的请求数
    Reading: 当前状态,正在读取客户端请求报文首部的连接的连接数
    Writing: 当前状态,正在向客户端发送响应报文过程中的连接数
    Waiting: 当前状态,正在等待客户端发出请求的空闲连接数
    

    ngx_http_log_module

    指定日志格式记录请求

    log_format name string ...; 	# string可以使用nginx核心模块及其它模块内嵌的变量
    
    access_log off; #禁止访问日志
    access_log path [format[buffer=size][gzip[=level]][flush=time][if=conditon]];
    
    访问日志文件路径,格式及相关的缓冲配置buffer=size flush=time
    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  logs/access.log  main;
    }
    
    缓存各日志文件相关的元数据信息
    open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
    	max: 缓存的最大文件描述符数量
    	min_uses: 在inactive指定的时长内访问大于等于此值方可被当作活动项
    	inactive: 非活动时长
    	valid: 验证缓存中各缓存项是否为活动项的时间间隔
    

    第三方模块

    第三方模块是对nginx的功能扩展,第三方模块需要在编译安装nginx的时候使用参数--add-module=PATH指定路径添加。

    开源echo模块

    编译第三方模块进去

    yum install pcre-devel openssl-devel zlib-devel gcc git -y
    useradd -r -s /sbin/nologin nginx
    git clone https://github.com/openresty/echo-nginx-module.git /usr/local/src/
    mkdir /data/nginx -p
    
    ./configure --prefix=/data/nginx --user=nginx --group=nginx 
    --with-http_ssl_module 
    --with-http_v2_module 
    --with-http_realip_module 
    --with-http_stub_status_module 
    --with-http_gzip_static_module 
    --with-pcre 
    --with-stream 
    --with-stream_ssl_module 
    --with-stream_realip_module  
    --add-module=/usr/local/src/echo-nginx-module
    
    加上:
             location /echo {
                echo "hello world";
                default_type text/html;
            }
    启动:
    /data/nginx/sbin/nginx
    浏览器访问Ip/echo,会显示出hello world
    

    nginx变量使用

    nginx的变量可以在配置文件中引用,作为功能判断或者日志等场景使用,变量可以分为内置变量和自定义变量,内置是由nginx模块自带,通过变量可以获取到众多的与客户端访问相关的值

    常见内置变量

    $remote_addr; 存放客户端的地址,注意是客户端的公网IP
    $args; 变量中存放了URL中的指令如http://www.xx.com/blog/list?id=20&name=xxx,id=20&name=xxx就是$args
    $document_root; 保存了针对当前资源的请求的系统根目录,如/data/nginx/html
    

    关于favicon.ico

    favicon.ico是浏览器收藏网站时显示的图标,当使用浏览器访问页面时,浏览器会自己主动发起请求获取页面的favicon.ico文件,但是文件不存在时,服务器会记录404,浏览器也会显示404报错

    解决方案:

    • 服务器不记录此访问日志

      location = /favicon.ico {

      ​ log_not_found off; 文件没发现事件不记录error_log

      ​ access_log off; 不记录access_log

      }

    • 将图标保存到指定目录访问

      location ~ ^/favicon.ico$ {

      ​ root html;

      }

    每天进步一点点
  • 相关阅读:
    java并发编程(五)——线程池
    java并发编程(四)——无锁
    java并发编程(三)——java内存模型
    java并发编程(二)——加锁
    java并发编程(一)——进程与线程
    java中的异常和处理机制
    使用JDK自带的keytool工具生成证书
    JAVA 制作证书
    网络安全之证书相关概念
    maven之.lastUpdated文件
  • 原文地址:https://www.cnblogs.com/Otiger/p/14581153.html
Copyright © 2011-2022 走看看