NginX 学习笔记

前言:这是一些学习NginX时的笔记,过去两年里零零散散地记录在本子上,今天偶然发现,就打算重新整理一下,也方便自己日后查阅。里面内容多多少少会有过时的情况,如果出现错误还希望指正。

NginX安装

注意,安装NginX的时候:
1.configure时添加模块
2.编译前安装各种模块满足需求
然后再开始安装主体部分:
wget [Nginx Address]

tar -vzxf [NginX install package]

cd [Nginx install package extracted direction]

./configure --prefix=/[install target direction] --with-http_stub_status_module --with-http_ssl_module

make && make install
无情小提示:在配置[./configure]时,若提示缺少XX程序,还得去补齐。

NginX信号控制

Command Usage
TERM, INT Quick shutdown
QUIT Gracefully shutdown
HUP Configuration reload, start the new worker processed with a new configuration, gracefully shutdown the old worker processes
USR1 Reopen the log files
USR2 Upgrade executable on the fly
WINCH Gracefully shutdown the worker processes
使用方法:
kill -[Command] [NginX master process] | [$( cat /usr/local/nginx/logs/nginx.pid )]

NginX配置文件概览

刚装完NginX的时候,大部分功能都是被默认关闭的,需要我们一个个打开它,这里可以使用正则简化步骤,但是这种方法会把注释也一起删除,真令人头大。另外,如果觉得想给插入的参数分文件调用,可以使用include [filename]的方法。
# egrep -v "#|^$" nginx.conf.default > nginx.conf
  • 全局区
    worker_process 1; //  Set the number of worker process, which need the number of CPU multiply its core
    
  • Event域
    Event{
      worker_connections 1024; // how many connections are allowed by one worker.
    }
    
  • Http域
    http{ // Main segment of configuring http server
      Server_1{ // The segment of virtual host, set listen port and server name
          Location{ // Locate the index file or bypass address
          }
      }
    }
    
    其中:Location域分为精准匹配,一般匹配和正则匹配。一般匹配时依照贪心算法进行匹配,正则匹配时从上到下依次逐行进行。

NginX上的日志文件

位于Server段的配置信息
access_log logs/access.log main; // Log NginX running information at logs/access.log in MAIN format
log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; // It defines what MAIN FORMAT mean

NginX中的Rewrite模块

  • 常用的命令
    if ( [Condition] ){ [Execute these statements if condition is TRUE] } // Judging condition in if statement
    set $[variable name] [variable] // Setting a var
    return [status code] // Returning a return value
    break // Jumping out of rewrite module
    rewrite [target regexp] [source file] // Rewriting the target address
    
  • 注意事项
    1. 在使用 rewrite 之后应使用 break 语句,否则会造成循环重定向。
    2. if中判断条件的变量名可在nginx目录下的 conf/fastcgi.conf 中可查。
    3. rewrite模块可使用在各种需要转发的作用域中。

在NginX中开启 Gzip压缩

  • 简明工作原理:
    浏览器请求给服务端,请求头中声明可以接受各种各样的压缩算法,问服务器提供啥。
    服务器把自家翻了一遍,发现竟然支持Gzip!回传数据时也不告诉浏览器支持啥了,直接把内容用gzip方式压缩发给浏览器,然后和浏览器说,我使用Gzip压缩的。
    浏览器接收gzip压缩内容然后解码Gzip。
  • 常用参数(把这些配置信息写在Server域或者全局域都行。)
    gzip on|off;  // Turns on or off Gzip
    gzip_buffers 32 4K | 16 8K // Sets the number and size of buffers
    gzip_comp_level [1-9] // Compression level, acceptable values are in the range from 1 to 9. By default, it sets as 6.
    gzip_disable // Disables gzipping of responses for requests with UA header fields matching any of the specified RegExp.
    gzip_min_length 200 // Sets the minimum length of a response that be about to gzip
    gzip_http_version 1.0|1.1 // Adapts to which http protocol version
    gzip_proxied off // Appoints proxy server and how it works.
    gzip_types text/plain  application/xml // Enables certain type of file will be gzipped
    gzip_vary on|off  // Inserts the Vary: Accept-Encoding”header or not when response.
    
  • 过小的静态资源可以不必开启Gzip压缩(即调整最小压缩长度)
  • 压缩率较低的二进制文件可以不必开启Gzip压缩(即指定压缩文件类型)
  • 简单范例
    gzip on;
    gzip_http_version 1.0;
    gzip_disable "MSIE [1-6].";
    gzip_types text/plain application/x-javascript text/css text/javascript application/x-httpd-php image/jpeg image/gif image/png;
    

NginX设置前端反向代理

NginX通常一般用于处理静态文件,如果遇到一些需要改动数据库的内容则转发给后端其他程序处理,比如Gunicorn。用法: proxy_pass [protocol]://[ip address]:[port number]
值得提醒的是,反向代理也会造成后端识别请求时将前反视作请求者造成日志记录错误,因此还需要在转发中添加 header X-Forwarded-For 来正确识别源地址请求。
location ~ \.jpg$ {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header   Host    $host:$server_port;
        proxy_set_header   X-Real-IP   $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
}

NginX设置负载均衡

NginX的负载均衡功能依赖于ngx_http_upstream_module模块,支持的代理方式有proxy_pass, fastcgi_pass, memcached_pass。
负载均衡一般分为二层,三层,四层和七层。其中后两者最常用,大多数情况下NginX使用的是基于TCP协议的四层负载均衡。这也导致了其传入的参数只能是IP地址,不能为域名或局域网内的主机名。
基本概流程是使用Upstream模块,制定绑定域名之后并起一个组名,然后将请求反向代理到该组。反向代理服务器如果有多台,NginX会自动形成负载均衡。这里一般指静态资源负载均衡。
当开启ip_hash方法时,热备不能使用。该调度算法可以解决动态网页session共享问题。但有时会导致IP请求分配不均,无法保证1:1的负载均衡。
upstream imgServer{
    # ip_hash;
    server 127.0.0.1:81 weight=5 max_fails=2 fail_timeout=30s;
    server 127.0.0.1:82 weight=5 max_fails=2 fail_timeout=30s;
    server 127.0.0.1:82 weight=1 max_fails=2 fail_timeout=30s backup; // hot backup
}

server {
    listen 81;
    server_name localhost;
    root html/imgA/
}

server {
    listen 82;
    server_name localhost;
    root html/imgA_bak/
}

server {
    listen 80;
    server_name localhost;
    root html/;
    location ~* \.(jpg | jpeg | gif | png)$ {
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://imgServer;
    }
}
NginX中默认的负载均衡算法为WRR(weight round-robin),即按权重轮询,权重越大,请求次数越多。当然这种方法不能很好地适配于大多数的生产环境,因此需要在NginX安装其他模块因地制宜。
小插曲,负载均衡算法分为两类:静态和动态。静态常见的有轮询,比率和优先权等。动态负载均衡算法包括:最少连接数,最快响应速度,观察法,预测法,动态性能分配,动态服务器补充,服务质量,服务类型,规则模式等。

NginX上第三方模块的安装和编译

以安装Upstream Consistent Hash为例,这个使用这个模块需要先安装memcached。
重新编译安装一遍NginX,在编译的时候添加 --add-module 指令。举例:
./configure --prefix=/etc/nginx/ --add-module=[target folder]

pkill -9 nginx // To avoid some unexpected error, such as creating a folder which named nginx.old

make && make install

Nginx 开启 HTTP 验证

  1. 在 Nginx 中的 Location 字段中添加以下内容
    auth_basic           "my site";
    auth_basic_user_file /etc/nginx/.htpasswd;
    
  2. 创建 HTTP 验证的加密文件
    echo -e "$USERNAME:`openssl passwd -apr1 -salt 5641 $OPSPASSWD`" >> /etc/nginx/.htpasswd
    

可能会用上的Linux命令

  • 测试NginX的测试文件是否有效
    nginx -t
    
  • 检测端口占用
    netstat -ant // Checking which port already in used
    netstat -tunlp | grep [port Num.] //Checking specific port whether in used
    lsof -i:[port Num.] //lsof is an another tool which  need download in certain linux
    
  • 关闭进程
    kill -9 [process Num.]
    kill -9 [process keyword]
    
  • 查看进程号
    ps aux | grep nginx
    

参考资料

评论