美文网首页转载部分
nginx开发终级指南

nginx开发终级指南

作者: 小小的小帅 | 来源:发表于2019-05-30 11:42 被阅读0次

    Nginx 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。

    参考网址

    nginx中文文档:链接

    下载:

    官方下载stable版本:http://nginx.org/
    下载地址: http://nginx.org/download/nginx-16.0.tar.gz

    安装

    1、安装准备
    nginx依赖于pcre库,要先安装pcre
    yum install pcre pcre-devel
    安装c++编译环境
    yum install gcc-c++
    yum install -y zlib-devel
    2、下载
    cd /usr/local/src/
    wget http://nginx.org/download/nginx-1.16.0.tar.gz
    tar -zxvf nginx-1.16.0.tar.gz
    3、指定编译目录
    cd nginx-1.16.0
    ./configure --prefix=/usr/local/nginx
    make && make install

    • 若发现依赖缺少,可更新依赖,这里首先安装系统常用的支持库。那么在安装的时候就会减少很多的错误的出现。
    yum install -y gcc gdb strace gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs patch e2fsprogs-devel krb5-devel libidn libidn-devel openldap-devel nss_ldap openldap-clients openldap-servers libevent-devel libevent uuid-devel uuid mysql-devel# yum install -y gcc gdb strace gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs patch e2fsprogs-devel krb5-devel libidn libidn-devel openldap-devel nss_ldap openldap-clients openldap-servers libevent-devel libevent uuid-devel uuid mysql-devel
    以及必要ssl功能模块
    yum -y install automake autoconf libtool make gcc gcc-c++  pcre-devel openssl openssl-devel  zlib-devel  perl-Digest-SHA1.x86_64
    
    • 若报时间戳错误,修改时间即可
      date -s '2019-05-30 13:59:00'
      clock -w

    启动

    • 目录结构分析
      cd /usr/local/nginx, 看到如下4个目录
      ... conf 配置文件
      ... html 网页文件
      ... logs 日志文件
      ... sbin 主要二进制程序
    • 命令
      启动命令:./sbin/nginx
      其他命令:./sbin/nginx -s stop(quit、reload)
      查看nginx安装路径:whereis nginx
      查看nginx安装进程:ps -ef|grep nginx
    • 检查配置是否正常, 查看nginx现在的模块
      ./sbin/nginx -t
      ./sbin/nginx -V


      检查配置.png

    Nginx的信号控制

    • 语法


    • 具体语法:

    kill -信号选项 nginx的主进程号
    kill -信号控制 `cat /xxx/logs/nginx.pid`
    优雅关闭:
    kill -QUIT `cat /usr/local/nginx/logs/nginx.pid`
    重读nginx.conf配置:
    kill -HUP `cat /usr/local/nginx/logs/nginx.pid`
    重读日志:
    kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
    
    

    nginx配置

    配置简介
    http { 
    // 这是虚拟主机段
         Server1 { 
                Location {  //定位,把特殊的路径或文件再次定位 ,如image目录单独处理
                }             /// 如.php单独处理
         }
         Server2 {
         }
    }
    
    全局区
    • 有1个工作的子进程,可以自行修改,但太大无益,因为要争夺CPU,一般设置为 CPU数*核数
      worker_processes 1;
    • 全局默认配置日志和pid存储地方,日志也可根据server
      error_log logs/error.log;
      error_log logs/error.log notice;
      error_log logs/error.log info;
      pid logs/nginx.pid;
    • 配置nginx连接的特性,这是指 一个子进程最大允许连1024个连接
      Event {
      worker_connections 1024;
      }
    http区
    • 默认日志格式 main格式
     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;

    • keepalive_timeout时间 默认65s,可以根据情况设置大些;
      keepalive_timeout 65;

    • gzip压缩 默认开启
      gzip on;
      gzip_buffers 32 4k;
      gzip_comp_level 6;
      gzip_min_length 4000;
      gzip_types text/css text/xml application/x-javascript;

    • 设定请求缓冲
      client_header_buffer_size 204800k;
      large_client_header_buffers 4 10240k;
      client_max_body_size 204800k;

    • 连接时长
      fastcgi_connect_timeout 600s;
      fastcgi_read_timeout 600s;
      fastcgi_send_timeout 600s;

    • 文件缓存
      fastcgi_buffer_size 256k;
      fastcgi_busy_buffers_size 256k;
      fastcgi_buffers 8 128k;
      fastcgi_temp_file_write_size 256k;

    • upstream配置 可用include引用
      include /conf/upstream.conf

    • 在/usr/local/nginx/conf/下新建conf/upstream.conf文件

    upstream backend {
            #权重 重试次数  失败timeout时间
             server 192.168.1.11:8080 weight=1 max_fails=2 fail_timeout=4s;
         #server 192.168.3.102:8080;
     }
    
    server区
    • 监听端口
      listen 80;
    • 域名,默认为本机 localhost
      server_name localhost;

    -声明log log位置 log格式;
    access_log logs/host.access.log main;

    location区

    location语法 匹配优先级,精准>正则>普通

    location [=|~|~*|^~] /uri/ { … }
    = 开头表示精确匹配
    ^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。
    ~ 开头表示区分大小写的正则匹配
    ~* 开头表示不区分大小写的正则匹配
    !~和!~*分别为区分大小写不匹配及不区分大小写不匹配 的正则
    
    • 请求timeout 连接时长 发送时长 读取时长
      proxy_connect_timeout 600s;
      proxy_send_timeout 600s;
      proxy_read_timeout 600s;
    图片或文件静态代理

    目录 /home/centos/app/staff
    location /staff {
    root /home/centos/app(例子);
    index index.html index.htm;
    }

    nginx配置 cpu4核 简易配置
    #user  nobody;
    worker_processes  4;
    
    #error_log  logs/error.log;
    #error_log  logs/error.log  notice;
    #error_log  logs/error.log  info;
    
    #pid        logs/nginx.pid;
    
    
    events {
        worker_connections  1024;
    }
    
    
    http {
        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        on;
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
        #gzip  on;
    
        upstream backend {
            #权重 重试次数  失败timeout时间
             server 192.168.1.11:8080 weight=1 max_fails=2 fail_timeout=4s;
             #server 192.168.3.102:8080;
           }
    
        server {
            listen       80;
            server_name  localhost;
    
            #charset koi8-r;
    
            #access_log  logs/host.access.log  main;
    
            location / {
                root   html;
                index  index.html index.htm;
            }
        
        location  /jenkins/ {
                proxy_pass http://backend; #反向代理,代理哪个应用服务器----②
                proxy_set_header Host $host;#此下三行设置把客户端的真实ip传给后端,可省
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                root   html;#请求到达nginx服务器后,分发不出去,会去nginx安装目录root下找页面
                index  index.html index.htm;#默认找index.html,可自定义页面
            }
            #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 {
                root   html;
            }
    
            # 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 {
        #    listen       443 ssl;
        #    server_name  localhost;
    
        #    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;
    
        #    location / {
        #        root   html;
        #        index  index.html index.htm;
        #    }
        #}
    }
    

    nginx日志切割

    • 分析
      shell+定时任务+nginx信号管理,完成日志按日期存储
    • 实现
      凌晨00:00:01,把昨天的日志重命名,放在相应的目录下
      再USR1信息号控制nginx重新生成新的日志文件

    阿里云健康检查插件:

    1. 方式一
      https://pan.baidu.com/s/1gfxppcCto9R_IOGVe2q0UQ 提取码:u888
    2. 方式二
    wget https://codeload.github.com/yaoweibin/nginx_upstream_check_module/zip/master
    unzip master
    ll -d nginx_upstream_check_module-master
    
    • 安装
    1. 安装包放到 /usr/local/src/目录下
      cd /usr/local/src/
      unzip nginx_upstream_check_module-master.zip
    2. 进入 nginx 目录, 并用 patch 命令 对源文件打补丁
      cd nginx-1.6.0
      yum -y install patch
      patch -p1 < ../nginx_upstream_check_module-master/check_1.5.12+.patch
      如出现错误可查看 /usr/local/src/nginx-1.16.0/src/http ,可能是nginx版本与patch不对应
    3. 有yum安装情况下:
      /usr/local/src/nginx-1.6.0
      ./configure --prefix=/usr/local/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --with-http_realip_module --with-http_addition_module --with-http_gzip_static_module --with-http_random_index_module --with-http_stub_status_module --with-http_sub_module --with-http_dav_module --with-http_ssl_module --add-module=../nginx_upstream_check_module-master/
      依赖缺失情况一
    ./configure: error: the HTTP rewrite module requires the PCRE library.
    You can either disable the module by using --without-http_rewrite_module
    option, or install the PCRE library into the system, or build the PCRE library
    statically from the source with nginx by using --with-pcre=<path> option.
    
    1. 依赖安装
      yum -y install pcre-devel
      yum -y install openssl openssl-devel
      再次configure,configure成功,如下
    Configuration summary
      + using system PCRE library
      + using system OpenSSL library
      + using system zlib library
    
      nginx path prefix: "/usr/local/nginx"
      nginx binary file: "/usr/local/nginx/sbin/nginx"
      nginx modules path: "/usr/local/nginx/modules"
      nginx configuration prefix: "/usr/local/nginx/conf"
      nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
      nginx pid file: "/usr/local/nginx/logs/nginx.pid"
      nginx error log file: "/usr/local/nginx/logs/error.log"
      nginx http access log file: "/usr/local/nginx/logs/access.log"
      nginx http client request body temporary files: "client_body_temp"
      nginx http proxy temporary files: "proxy_temp"
      nginx http fastcgi temporary files: "fastcgi_temp"
      nginx http uwsgi temporary files: "uwsgi_temp"
      nginx http scgi temporary files: "scgi_temp"
    
    
    1. 编译安装
      make && make install
      cd /usr/local/nginx/
    • 添加配置
    1. 在upstream 中配置
      interval=3000:间隔3秒检查一次,rise=2:检查2次ok后端节点up,fall=3:三次。
      检查失败后端节点down,timeout=3000:超时时间3秒,type=http:发http检查请求类型。
      port=8080检查端口,可省略,默认和server 中的端口一致。
      以/jenkins为例
    check interval=3000 rise=2 fall=5 timeout=1000 port=8080;
    check_http_send "GET /jenkins HTTP/1.0\r\n\r\n";
    check_http_expect_alive http_2xx http_3xx;
    
    • 在server中加
      location匹配,健康检查
            location /status { 
                check_status;
                access_log off;
                #allow SOME.IP.ADD.RESS;
                #deny all;
            }  
    

    访问:http://192.168.1.11/status

    阿里巴巴健康检查.png

    nginx HTTPS配置

    腾讯云域名注册

    腾讯云域名注册
    腾讯SSL证书手册
    腾讯SSL证书申请
    腾讯云处理订单
    腾讯域名修改
    域名监测平台

    SSL数字证书

    SSL数字证书Nginx配置部署指导
    阿里SSL证书下载

    Nginx 证书部署

    证书安装

    1. 将已获取到的1_www.domain.com_bundle.crt 证书文件和 2_www.domain.com.key 私钥文件拷贝到 Nginx 服务器的 /usr/local/nginx/conf 目录下。
      命令1、./configure --with-http_ssl_module //重新添加这个ssl模块

    2. 更新 Nginx 根目录下的 ssl//nginx.conf 文件。修改内容如下:

      server {
           listen 443 ssl; 
           server_name hand-xies.com; #填写绑定证书的域名
           #ssl on;
           ssl_certificate ssl/1_www.hand-xies.com_bundle.crt;
           ssl_certificate_key ssl/2_www.hand-xies.com.key;
           ssl_session_timeout 5m;
           ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #按照这个协议配置
           ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;#按照这个套件配置
           ssl_prefer_server_ciphers on;
              location   /staff {
              proxy_pass http://backend; #反向代理,代理哪个应用服务器----②
              proxy_set_header Host $host;#此下三行设置把客户端的真实ip传给后端,可省
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              root   html;#请求到达nginx服务器后,分发不出去,会去nginx安装目录root下找页面
              index  index.html index.htm;#默认找index.html,可自定义页面
          }
       }
      

      配置文件的主要参数说明如下:

      • listen 443:SSL 访问端口号为 443
      • ssl on:启用 SSL 功能
      • ssl_certificate:证书文件
      • ssl_certificate_key:私钥文件
      • ssl_protocols:使用的协议
      • ssl_ciphers:配置加密套件,写法遵循 openssl 标准
    • 重启 Nginx。
      即可使用 https://hand-xies.com/staff/ 进行访问。
      访问https.png

    使用全站加密,HTTP 自动跳转 HTTPS(可选)

    对于用户不知道网站可以通过 HTTPS 方式访问的情况,我们可以通过配置服务器,让其自动将 HTTP 的请求重定向到 HTTPS。
    您可以在页面中添加 JS 脚本,也可以在后端程序中添加重定向,还可以通过 Web 服务器实现跳转。
    若您在编译时没有去掉 pcre,Nginx 支持 rewrite 功能。您可在 HTTP 的 server 中增加 rewrite ^(.*) https://$host$1 permanent;,即可将80端口的请求重定向为 HTTPS。

    server {
        listen 80;
        server_name hand-xies;// 你的域名
        rewrite ^(.*)$ https://$host$1 permanent;// 把http的域名请求转成https
    }
    
    • 配置https
      参考
      nginx的配置文件是nginx.conf,里面的配置内容有以下,为了容易明白,我都加上了注释。
    #user  nobody;
    worker_processes  4;
    
    #error_log  logs/error.log;
    #error_log  logs/error.log  notice;
    #error_log  logs/error.log  info;
    #pid        logs/nginx.pid;
    
    events {
        worker_connections  1024;
    }
    
    
    http {
        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        on;
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
        #gzip  on;
        ##包含upstream配置项
        include conf.d/upstream.conf;
        
        server {
             listen 443 ssl; 
             server_name hand-xies.com; #填写绑定证书的域名
             #ssl on;
             #定义服务器的默认网站根目录位置
             #root /usr/local/nginx/html; 
             ssl_certificate ssl/1_www.hand-xies.com_bundle.crt;
             ssl_certificate_key ssl/2_www.hand-xies.com.key;
             ssl_session_timeout 5m;
             ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #按照这个协议配置
             ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;#按照这个套件配置
             ssl_prefer_server_ciphers on;
             ##包含配置location
            include conf.d/location80.conf;
         }
        server {
            listen       80;
            server_name  hand-xies.com;
             rewrite   ^  https://$server_name$request_uri? permanent;
            ### 使用return的效率会更高 
            # return 301 https://$server_name$request_uri;
    
            #charset koi8-r;
    
            #access_log  logs/host.access.log  main;
            ##包含配置location
            include conf.d/location80.conf;
            
            #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 {
                root   html;
            }
    
        }
    
    }
    
    • 为了更好管理,我把location.conf和upstream.conf分离出来


      location和upstream.png
    • upstream.conf配置文件
    upstream backend {
        # 权重 重试次数  失败timeout时间
        server 129.28.104.226:8080 weight=1 max_fails=2 fail_timeout=4s;
        # server 192.168.3.102:8080;
        # interval=3000:间隔3秒检查一次,rise=2:检查2次ok后端节点up,fall=3:三次检查失败后端节点down,timeout=3000:超时时间3秒,type=
        # http:发http检查请求类型,port=8080检查端口,可省略,默认和server 中的端口一致。
        # HEAD后为项目端口后地址
        # check interval=3000 rise=2 fall=5 timeout=1000 port=8080;
        # check_http_send "GET /staff HTTP/1.0\r\n\r\n";
        # check_http_expect_alive http_2xx http_3xx;
    }
    
    • location.conf配置文件
    location /staff {
        proxy_pass http://backend; # 反向代理,代理哪个应用服务器----②
        proxy_set_header Host $host; # 此下三行设置把客户端的真实ip传给后端,可省
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        root html; # 请求到达nginx服务器后,分发不出去,会去nginx安装目录root下找页面
        index index.html index.htm; # 默认找index.html,可自定义页面
    }
    location / {
        proxy_pass http://backend; # 反向代理,代理哪个应用服务器----②
        proxy_set_header Host $host; # 此下三行设置把客户端的真实ip传给后端,可省
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        root html; # 请求到达nginx服务器后,分发不出去,会去nginx安装目录root下找页面
        index index.html index.htm; # 默认找index.html,可自定义页面
    }
    # 静态文件,nginx自己处理
    location ~ ^/(images|javascript|js|css|flash|media|static)/ {
        # 过期30天,静态文件不怎么更新,过期可以设大一点,
        # 如果频繁更新,则可以设置得小一点。
        expires 30d;
    }
    
    # 禁止访问 .htxxx 文件
    # location ~ /.ht {
    # deny all;
    # }
    # 健康检查
    # location /status {
    # check_status;
    # access_log off;
    # }                 
    
    • 配置文件写好后用nginx测试一下
      nginx -t

    • nginx日常操作命令
      nginx -t 测试配置文件
      nginx -s reload 修改配置后重载生效
      nginx -s reopen 重新打开日志文件
      nginx -s stop 快速停止
      nginx -s quit

    相关文章

      网友评论

        本文标题:nginx开发终级指南

        本文链接:https://www.haomeiwen.com/subject/lfzytctx.html