☞Nginx

Nginx



概述

NGINX is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. NGINX is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.

NGINX is one of a handful of servers written to address the C10K problem. Unlike traditional servers, NGINX doesn’t rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load. Even if you don’t expect to handle thousands of simultaneous requests, you can still benefit from NGINX’s high-performance and small memory footprint. NGINX scales in all directions: from the smallest VPS all the way up to large clusters of servers.

NGINX powers several high-visibility sites, such as Netflix, Hulu, Pinterest, CloudFlare, Airbnb, WordPress.com, GitHub, SoundCloud, Zynga, Eventbrite, Zappos, Media Temple, Heroku, RightScale, Engine Yard, MaxCDN and many others.

Nginx可以是:

  • httpd协议的web服务器,其对于静态资源有无与伦比的响应能力

  • 反向代理服务:代理FastCGI/uwSCGI/SCGI、httpd、imap4/pop3协议、tpc/udp协议

  • 缓存服务器:缓存动态资源

Nginx程序采用高度模块化设计,但早期不支持DSO机制,如今已支持模块动态装载和卸载;

  • 核心模块:core module

  • 标准模块:Standard HTTP modules、Optional HTTP modules、Mail modules、Stream modules、3rd party modules

Nginx处理事务的架构为mater/worker

  • master:负责加载配置文件,管理worker进程;

  • worker:处理N个用户的请求;

  • 缓存相关进程:cache loader、cache manager;

Nginx支持异步IO机制,协调master与worker之间的工作效率

  • 事件驱动、异步IO、非阻塞是Nginx最重要特性,这种由被调用者通过状态、通知或回调机制通知调用者被调用者的运行状态的机制使得Nginx能够处理大量的并发请求。

  • 阻塞型IO需等待数据加载过程的两阶段,处于挂起状态;非阻塞型IO无需等待第一阶段的磁盘加载过程,但仍需周期性检查数据是否已经准备好,属于第一阶段为忙等待,第二阶段仍为阻塞类型的IO,即进程在此期间无法处理任何请求。

  • 复用型IO使得进程不阻塞于第一阶段的系统IO上,而是阻塞在内核空间提供的复用IO上。同步IO虽无需等待第一阶段的IO,但第二阶段仍需阻塞加载数据,其回调机制使得进程在第一阶段是空闲的,因此一个进程可以处理多个请求;异步IO则使进程两个阶段都不阻塞,其事件驱动与异步IO架构,使得一个进程可处理更多的请求。

  • nginx.jpg

yum安装Nginx

  • 准备yum源或rpm包

#官方提供的yum仓库
vi /etc/yum.repos.d/nginx.repo
   [nginx]
   name=nginx repo
   baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/
   gpgcheck=0
   enabled=1
yum -y install nginx

#或下载最新的rpm包进行安装
yum -y install ./nginx.xx.rpm
  • 启动前的配置

cp /etc/nginx.conf{,.bak}
vi /etc/nginx.conf
cp /etc/nginx/conf.d/default.conf{,.bak}
vi /usr/share/nginx/html/admin/index.html
  • 启动nginx

nginx
ss -tnl | grep ":80\>"

编译安装Nginx

[官方wiki]http://nginx.org/en/docs/configure.html

  • 准备开发环境、依赖程序包

yum install pcre-devel openssl-devel zlib-devel
  • 创建 nginx 用户

useradd -r nginx
  • 获取源码包,编译安装

tar xf nginx-1.10.0.tar.gz

./configure --help      #获取编译帮助,有N多模块可选

./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_dav_module --with-http_stub_status_module --with-threads --with-file-aio

#编译结果
Configuration summary
 + using threads
 + using system PCRE library
 + using system OpenSSL library
 + md5: using OpenSSL library
 + sha1: using 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: "/etc/nginx"
 nginx configuration file: "/etc/nginx/nginx.conf"
 nginx pid file: "/var/run/nginx.pid"
 nginx error log file: "/var/log/nginx/error.log"
 nginx http access log file: "/var/log/nginx/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"

#开始编译
make -j2 && make install

#添加环境变量
echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
  • 命令使用

nginx -h
(1)nginx
(2)nginx -s signal: send signal to a master process: stop, quit, reopen, reload

主要文件路径

配置文件: 
/etc/nginx/nginx.conf/etc/nginx/conf.d/*.conf 
fastcgi uwsgi scgi等相关配置文件:fastcgi_params 
mime.types:支持的mimie类型:mime.types

程序文件: 
Excusetable:/usr/sbin/nginx/usr/sbin/nginx-debug 
Unit File:/usr/lib/systemd/system/nginx.service,/usr/lib/systemd/system/nginx-debug.service 
Modules:/usr/lib64/nginx/modules

站点:/usr/share/nginx, /usr/share/nginx/html, /usr/share/nginx/html/50x.html, /usr/share/nginx/html/index.html 
日志:/var/log/nginx 
缓存:/var/cache/nginx

主配置文件nginx.conf

配置文件有众多的指令组成,格式为:

  • directive value [value2 …];注意:指令必须以分号结尾

配置文件中的变量:

  • 内建变量:有Nginx模块引入,可直接引用

  • 自定义变量:set $variable value;

main block:全局配置段

main block:全局配置段
   ……                #正常运行必备的配置、优化性能等
#事件驱动相关的配置
event{
}

mail{
}

stream{
}

http/https 协议相关配置段

http{
   ……
   server的公共配置
   server{
       ……
   }:一个server一个虚拟主机
   server{
       server_name
       root
   location [OPERATOR] URL{
       alias
       ……
       if CONDITION{
           ……
           }
       }  
   }
}

性能优化初步

  • 【1】worker_cpu_affinity cpumask …; 
    worker_cpu_affinity auto [cpumask]; 
    cpumask:0101 1010;每worker进程使用一个十六进制位亲和最多4核心的CPU

  • 【2】worker_priority number 
    from -20 to 20, a negative number means higher priority

  • 【3】worker_rlimit_nofile number 
    the limit on the maximum number of open files (RLIMIT_NOFILE) for worker processes

调试、定位问题的配置

  • daemon on|off; 是否以守护进程运行在后台

  • master_process on | off; 是否以master/worker运行nginx,否则只运行master

  • error_log file [level]; 在各段或只在main中同一记录日志

events段配置

worker、method、accept_mutex

events{
       worker_connections number; #每worker最大并发连接数,worker_process * worker_connect为总并发
       use method;     #use epol,
       accept_mutex on|off     #处理新连接请求的方法,on为turn,off为通知所有worker,在httpd上会造成惊群问题造成上下文切换过载。关闭时用ngx-req-distr工具测试发现每个worker处理的请求数较平均。
}

http协议相关配置段

虚拟主机

    • 【1】server;定义虚拟主机,一般单独写在conf.d目录下

    server{
           listen ip[:port] | port
           server_name
           root
           location [OPERATOR] /url/{
               ……
           }
    }
    • 【2】listen address[:port] [default_server] [ssl] [http2 | spdy] [backlog=number] [sndbuf=size] [accept_filter=filter];

    • 【3】server_name name …;空白字符分隔开的多个name 

      1. *.example.com www.example.*:以 * 通配任意字符

      2. ~^www\d+\.example\.com$:以 ~ 匹配的正则表达式模式

      3. 优先级:精确 > *. 通配符 > 通配符 .* > 正则

    基于PORT、IP、Server Name的虚拟主机示例

    单个IP可定义多个不同PORT虚拟主机,单个IP的单个PORT可定义多个不同Server Name的虚拟主机。因此,常用的虚拟主机为基于PORT与Server Name的虚拟主机。

    vi /etc/nginx/conf.d/vhost.conf
       server {
       listen 8080;
       server_name localhost;
       root /data/nginx/port;
       }

       server {
       listen 10.1.253.69;
       server_name localhost;
       root /data/nginx/ip1;
       }
       server {
       listen 10.1.253.70;
       server_name www2.jasonmc.com;
       root /data/nginx/ip2;
       }

       server {
       listen 10.1.253.69;
       server_name www1.jasonmc.com;
       root /data/nginx/www1;
       }

       server {
       listen 10.1.253.69;
       server_name www2.jasonmc.com;
       root /data/nginx/www2;
       }

    与套接字相关的配置(sendfile、nodelay)

    • 【4】tcp_nodelay on | off;在keepalived模式下,当用户请求的资源较少时,默认把多个资源打包发送,虽省资源,但影响用户体验

    • 【5】sendfile on | off;内核级别直接封装用户请求的资源,不复制到进程内存再封装以提高响应速度

    定义路径相关配置

    • 【6】root path;设置web资源路径映射,指明url所对应在本地文件系统的路径,可在 http, server, locationduan定义,在//host/path --> Newpath/path/index.html

    • 【7】location @name { … } 
      在一个server中可有多个location,用于映射url到其他路径,nginx会根据请求的URI匹配一个最佳的路径 

      1. location [ = | ~ | ~* | ^~ ] uri { … } 
        =:对URI精确匹配,如www.exp.com/与www.exp.com/index.html将映射在不同的location中 
        ~:对URI正则表达式匹配,区分字符大小写 
        ~*:对URI正则表达式匹配,不区分大小写 
        ^~:对URI左半部分正则匹配,不区分大小写 
        /:不带符号将匹配没人要的URI 
        优先级:匹配范围小的优先级高 =, ^~, ~*/~, /

    定义 URL 对应的 root 示例

    vi /etc/nginx/conf.d/default.conf
           locaction /admin/ {
               root /data/nginx/;映射为/data/nginx/admin/index.html
           #或alias把//host/admin/index.html映射到/data/nginx/index.html
           }

    • 【8】alias path;定义在location中,与root的区别在于path直接映射为url的根,无需在路径中建立对应的目录。如//host/path –> Newpath/index.html

    • 【9】index file…;定义首页文件,可在http、server、locaton中定义,虚拟主机一般在server中定义。

    • 【10】error_page code … [=[response]] uri;错误码和错误页 
      Defines the URI that will be shown for the specified errors.

    定义错误页示例

    vi /etc/nginx/conf.d/default.conf
       error_page  404              /404.html;如果404 =200则响应码为200,ok

       location = /404.html{
           root /usr/share/nginx/html/error_page/;
       }
    • 【11】try_files file … uri; 
      try_files file … =code;

    客户端请求相关配置

    • 【12】keepalive_requests number;在一次长连接所允许的最大请求次数,默认100

    • 【13】keepalive_timeout timeout [header_timeout];保持连接超时时长,0表示禁止长连接,默认75s

    • 【14】keepalive_disable none | browser …;对哪种浏览器禁用长连接

    • 【15】send_timeout time;向客户端发送响应报文的超时时长

    • 【16】client_body_buffer_size size;缓冲请求报文的body部分,默认16k,超出则存在文件中

    • 【17】client_body_temp_path path [level1 [level2 [level3]]];超出内存缓冲16k,存储在磁盘路径中,索引方式采用目录分层结构,一般3层结构即可 

      1. client_body_temp_path /var/tmp/client_body 1 2 2;每层最多2个16进制位

    限定客户端速率与请求方法

    • 【18】limit_rate rate;默认0为不限制,单位bytes

    • 【19】limit_except method … { … };限制常用请求方法以外的请求方法允许谁使用

    除GET方法以外允许谁访问的示例

    server{
       limit_except GET {
           allow 192.168.1.0/32;
           deny  all;
       }
    }

    文件操作优化配置(ngx_http_core_module)

    • 【20】aio on | off | threads[=pool];异步IO,nginx的最大特性,提升性能

    • 【21】directio size | off;在Linux中,接收或加载的文件大小超过给定的size时,直接存取磁盘,不经过内存

    • 【22】open_file_cache max=N [inactive=time];超过max阀值或inactive之后,LRU算法进行清理非活动项,能够缓存文件描述符、大小、修改时间、目录结构、存在及权限信息 

      1. open_file_cache off;

    • 【23】open_file_cache_min_uses number;在inactive指定的时间活内动项被命中的次数

    • 【24】open_file_cache_valid time;缓存有效期的检查频率,活动还是非活动,默认60s

    • 【25】open_file_cache_errors on | off;

    基于ip的访问控制功能(ngx_http_access_module)

    • 【26】allow address | CIDR | unix: | all;

    • 【27】deny address | CIDR | unix: | all;

    基于用户的访问控制功能(ngx_http_auth_basic_module)

    • 【28】auth_basic string | off;

    • 【29】auth_basic_user_file file;

    用户验证示例

        location / {
           ……
           auth_basic "we need to authority.";
           auth_basic_user_file /etc/nginx/.ngxpasswd;
       }
    #生成验证所需的账号和密码,使用htpasswd工具
       yum install httpd-tools
       htpasswd -c -m /etc/nginx/.ngxpasswd tom
       htpasswd -m /etc/nginx/.ngxpasswd alice

    stub状态信息页(ngx_http_stub_status_module)

    • 【30】stub_status;在某一location中定义请求时自动生成相关信息

    stub_status配置示例

        location /basic_status {
           stub_status;
           access_log off;                 #location中暂定为无法阻断日志输出
       }
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    #输出的实时数据:
    Active connections: 291                 #当前连接数
    server accepts handled requests         #汇总的数据
        16630948 16630948 31070465
    Reading: 6 Writing: 179 Waiting: 106    #读取客户端报文、向客户端发送、等待客户端发送的几种连接数

    日志管理模块(ngx_http_log_module)

    The ngx_http_log_module module writes request logs in the specified format.

    常用内置变量

    1. $remote_addr, \$http_x_forwarded_for 记录客户端IP地址

    2. $remote_user 记录客户端用户名称

    3. $request 记录请求的URL和HTTP协议

    4. $status 记录请求状态

    5. $body_bytes_sent 发送给客户端的字节数,不包括响应头的大小; 该变量与Apache模块mod_log_config里的“%B”参数兼容

    6. $bytes_sent 发送给客户端的总字节数

    7. $connection 连接的序列号

    8. $connection_requests 当前通过一个连接获得的请求数量

    9. $msec 日志写入时间。单位为秒,精度是毫秒

    10. $pipe 如果请求是通过HTTP流水线(pipelined)发送,pipe值为“p”,否则为“.”

    11. $http_referer 记录从哪个页面链接访问过来的

    12. $http_user_agent 记录客户端浏览器相关信息

    13. $request_length 请求的长度(包括请求行,请求头和请求正文)

    14. $request_time 请求处理时间,单位为秒,精度毫秒; 从读入客户端的第一个字节开始,直到把最后一个字符发送给客户端后进行日志写入为止

    15. $time_iso8601 ISO8601标准格式下的本地时间

    16. $time_local 通用日志格式下的本地时间

    • 【31】log_format name string …; 
      日志格式,使用nginx内建变量ngx_http_core_module中被编译到core中的模块所提供的变量,Embedded Variables中有相关的描述

    • 【32】access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]]; 

      1. buffer=size:日志在内存缓存空间大小

      2. flush=time:指定缓存到磁盘的时间

      3. access_log off;

      4. access_log /path/to/log.gz combined gzip flush=5m;

    • 【33】open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time]; 
      缓存打开的日志文件描述符信息,加速日志文件元数据的操作 

      1. open_log_file_cache off;

      2. max:最大缓存文件描述符数量

      3. inactive:非活动时长,默认10s

      4. min_users:在inactive时间内,活动项应有的访问次数

      5. valid:验证缓存项是否为活动状态,根据inactive和min_users识别,默认60s

      6. open_log_file_cache max=1001 inactive=16s valid=60s min_users=2;

    log_format默认格式

    vi /etc/nginx/nginx.conf
       log_format compression '$remote_addr - $remote_user [$time_local] '
                              '"$request" $status $bytes_sent '
                       '"$http_referer" "$http_user_agent" "$gzip_ratio"';

    log_format适用于反向代理

    #nginx作为反向代理服务器,记录客户端真实ip及转发的日志信息
    log_format  main  
                   '$remote_addr - $remote_user [$time_local] "$request" '
                   '"$status" $body_bytes_sent "$http_referer" '
                   '"$http_user_agent" "$http_x_forwarded_for" '
                '"$gzip_ratio" $request_time $bytes_sent $request_length';

    log_format适用于SRCache缓存

    #分布式缓存SRCache相关的日志
    log_format srcache_log
               '$remote_addr - $remote_user [$time_local] "$request" '
               '"$status" $body_bytes_sent $request_time $bytes_sent $request_length '
               '[$upstream_response_time] [$srcache_fetch_status] [$srcache_store_status] [$srcache_expire]';

    log_format适用于json格式

    #记录json格式的日志,便于logstash分析日志
    log_format logstash_json '{ "@timestamp": "$time_local", '
                                '"@fields": { '
                                '"remote_addr": "$remote_addr", '
                                '"remote_user": "$remote_user", '
                                '"body_bytes_sent": "$body_bytes_sent", '
                                '"request_time": "$request_time", '
                                '"status": "$status", '
                                '"request": "$request", '
                                '"request_method": "$request_method", '
                                '"http_referrer": "$http_referer", '
                                '"body_bytes_sent":"$body_bytes_sent", '
                     '"http_x_forwarded_for": "$http_x_forwarded_for", '
                            '"http_user_agent": "$http_user_agent" }
    }';

    ##经过http://jsonlint.com/转换之后非常便于阅读与分析
    {
       "@timestamp": "25/Oct/2016:15:15:38 +0800",
       "@fields": {
           "remote_addr": "192.168.1.26",
           "remote_user": "-",
           "body_bytes_sent": "9",
           "request_time": "0.000",
           "status": "200",
           "request": "GET / HTTP/1.1",
           "request_method": "GET",
           "http_referrer": "http://www.pma.com",
           "body_bytes_sent": "9",
           "http_x_forwarded_for": "-",
           "http_user_agent": "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.21 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2"
       
    }
    }                      

    URL重写(ngx_http_rewrite_module)

    能够实现将用户请求的URI基于regex进行匹配,并replacement为新的URI 
    注意:在同一级配置块中的多个rewrite规则将按顺序逐一匹配,每替换一次就产生新的URI,如果后续的rewrite能够继续匹配新的URI,直到最终的替换结果,可能出现无限循环。因此,[flag]标记可避免这种情况。

    status: 
    301:永久重定向,对该URI显示为Moved Permanently,可被缓存(from cache) 
    302:临时从定向,对该URI显示为Moved Temporarily,一般不被Browser缓存

    • 【rewrite flag】:默认为last,由服务端nginx系统不断循环重新匹配,直到无法再匹配到 

      1. last:在一个location中匹配到URI就停止当前循环,把新的URI在location从头开始匹配

      2. break:在一个location中匹配到URI就停止当前循环

      3. redirect:重写URI后以临时重定向发送给客户端,客户端请求新的URL,code为302

      4. permanent:重写URI后以永久从定向方式发送给客户端,客户端请求新的URL,code为301

    • 【1】rewrite regex replacement [flag];

    • 【2】rewrite_log on | off;记录重写日志

    location中URL重写示例

    vi /etc/nginx/conf.d/default.conf
       location / {
           root   /usr/share/nginx/html;
           index  index.php index.html index.htm;
           rewrite ^/fz(.*) https://www.google.com redirect;
           #rewrite ^/(.*)$ https://www.pma.com/$1;     #全站https
       }
    • 【3】return code [text];return code URL;return URL; 
      Stops processing and returns the specified code to a client.

    • 【4】if (condition) { … } 
      引入一个新的配置段,条件满足时执行段内指令,运用在server、location中 
      condition: 

      1. 比较操作符 
        = = 
        != 
        ~:模式匹配,区分字符大小写; 
        ~*:模式匹配,不区分字符大小写; 
        !~:模式不匹配,区分字符大小写; 
        !~*:模式不匹配,不区分字符大小写;

      2. 文件及目录存在性判断 
        -e, !-e 
        -f, !-f 
        -d, !-d 
        -x, !-x

    • 【5】set $variable value; 
      自定义变量,系统变量可在ngx_http_core_module的Embedded Variables中查看

    location中if条件示例

        if ($http_user_agent ~ MSIE) {
           rewrite ^(.*)$ /msie/$1 break;
       }
       if ($slow) {
           limit_rate 10k;
       }
       if ($invalid_referer) {
           return 403;
       }  
       if ($request_method = POST) {
           return 405;
       }

    gzip压缩功能ngx_http_gzip_module

    The ngx_http_gzip_module module is a filter that compresses responses using the “gzip” method.

    • 【1】gzip on | off;

    • 【2】gzip_comp_level level; 
      Sets a gzip compression level of a response. the range from 1 to 9.

    • 【3】gzip_disable regex …; 
      Disables gzipping of responses for requests with “User-Agent” header fields matching any of the specified regular expressions.

    • 【4】gzip_min_length length; 
      Sets the minimum length of a response that will be gzipped.

    • 【5】gzip_buffers number size; 
      Sets the number and size of buffers used to compress a response.

    • 【6】gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any …;由nginx作为代理服务器,转发响应报文时在何种情况下启用压缩功能。 

      1. no-cache, no-store, private:大致表示对不缓存的内容启用压缩,报文中有三者中任一值都启用压缩。

    • 【7】gzip_vary on | off;

    GZip压缩示例

    http{
       gzip on;
       gzip_comp_level 5;
       #gzip_disable .*MSIE.*;
       gzip_type text/plain, text/css, text/xml;
       gzip_min_length 1K;
       gzip_vary on;            #增加报文Vary:Accept-Encoding
       gzip_disable Chrome;    
    }

    #拷贝文件做测试
    cp /var/log/messages /usr/share/nginx/html/messages.html
    chmod +x

    #测试
    curl -I http://ip/file      
       Vary:Accept-Enconding      #响应报文告诉客户端支持压缩
    curl --compressed -I http://ip/file
       Vary:gzip                  #使用gzip压缩,明显减小Content-Length

    fastcgi反向代理(ngx_http_fastcgi_module)

    The ngx_http_fastcgi_module module allows passing requests to a FastCGI server. 
    nginx作为反向代理服务器,实现lnmp的web框架

    • 【1】fastcgi_pass address;映射fastcgi server在location

    • 【2】fastcgi_index name;

    • 【3】fastcgi_param parameter value [if_not_empty];传递给后端服务器的变量值,在fastcgi_params文件中定义 
      fastcgi_param QUERY_STRING /path/$query_string;把nginx的query_string传递给fpm的QUERY_STRING变量

    FastCGI代理至fpm示例

    vi /etc/nginx/conf.c/default.conf
    server {    
           index index.php index.html index.htm

           location ~ \.php$ {
               root           /usr/share/nginx/html;
               fastcgi_pass   127.0.0.1:9000;
               fastcgi_index  index.php;
               fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html/$fastcgi_script_name; 或/$fastcgi_script_name
               include        fastcgi_params;  
            }

            location ~* ^/(fpm-status|ping)$ {
               fastcgi_pass 127.0.0.1:9000;
               fastcgi_param  SCRIPT_FILENAME $fastcgi_script_name;
               include        fastcgi_params;                      
            }
    }
    • 【4】fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time]; 
      定义fastcgi的缓存,缓存位置为磁盘上的文件系统路径,由path指定 

      1. levels=level1:level2:缓存目录的层级结构,16进制位数,每层最多2位 
        缓存的存放方式:对URL做hash运算,md5值的倒数几位作为存放目录层级结构的路径,hash表使用keys_zone定义,记录了key/value的映射关系

      2. keys_zone=name:size:key/value使用的内存区域名及大学

      3. inactive=time:非活动时长

      4. max_size=size:磁盘上用于缓存fastcgi数据的上限,放在SSD中可加速

    • 【5】fastcgi_cache zone | off;开启代理缓存,使用keys_zone定义的区域

    • 【6】fastcgi_cache_key string;定义用作缓存项的key字符串

    • 【7】fastcgi_cache_methods GET | HEAD | POST …;为哪些请求方法启用缓存

    • 【8】fastcgi_cache_min_uses number;活动项的最少命中次数

    • 【9】fastcgi_cache_valid [code …] time;不同响应码的缓存时长,如404被缓存5分钟

    • 【10】fastcgi_keep_conn on | off;向后端fpm服务器开启保存连接,应对大量并发访问

    开启FastCGI缓存示例

    vi /etc/nginx/nginx.conf
       http{
           fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2:2 keys_zone=fcgi:20m inactive=120s;
       }

    vi /etc/nginx/conf.d/default.conf
       location ~ \.php$ {
           root           /usr/share/nginx/html;
           fastcgi_pass   127.0.0.1:9000;
           fastcgi_index  index.php;
           fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html/$fastcgi_script_name;
           include        fastcgi_params;  
           fastcgi_cache fcgi;           #在http{}中定义的key_zone=fcgi
           fastcgi_cache_key $request_uri;
           fastcgi_cache_valid 200 302 10m;
           fastcgi_cache_valid 301 1h;
           fastcgi_cache_valid any 1m;
        }

    #缓存目录在/var/cache/nginx/fastcgi_cache中,自动生成该目录

    ssl模块(ngx_http_ssl_module)

    • 【1】ssl on | off;允许HTTPS protocol for the given virtual server.

    • 【2】ssl_certificate file;

    • 【3】ssl_certificate_key file;

    • 【4】ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; 
      支持的ssl版本,建议使用1.1,默认为后三个

    • 【5】ssl_session_cache off | none | [builtin[:size]] [shared:name:size]; 

      1. builtin[:size]使用openssl内建的缓存,此缓存为每个worker进程私有

      2. shared:name:size在多个worker进程间使用共享内存,便于切换

    • 【6】ssl_session_timeout time;缓存的有效时长

    开启https的phpMyAdmin示例

    【配置虚拟主机https协议的PhpMyAdmin】
    vi /etc/nginx/conf.d/pma_ssl.conf
       server {
           listen 443 ssl;
           server_name www.pma.com;
           location / {
               root /usr/share/nginx/vhost/htdoc/pma;
               index index.php
           }

           location ~* \.php$ {
               root           /usr/share/nginx/vhost/htdoc/pma;
               fastcgi_pass   127.0.0.1:9000;
               fastcgi_index  index.php;
               fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/vhost/htdoc/pma/$fastcgi_script_name;
               include        fastcgi_params;
               fastcgi_cache fcgi;
               fastcgi_cache_key $request_uri;
               fastcgi_cache_valid 200 302 10m;
               fastcgi_cache_valid 301 1h;
               fastcgi_cache_valid any 1m;
           }

           ssl on;
           ssl_certificate /etc/httpd/certs/www_pma_com.crt
           ssl_certificate_key /etc/httpd/certs/httpd.key
           ssl_session_cache shared:sslcache:10m;

           access_log /var/log/nginx/access_json.log logstash_json;

           valid_referers none block server_names *.pma.com pma.* ~\.pma\.;

           if ($invalid_referer) {
               return 403;
           }
       }
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    #全站https,把80端口跳转到固定链接
    vi /etc/nginx/conf.d/default.conf
       rewrite ^/(.*)$ https://www.pma.com/$1

    资源防盗链模块(ngx_http_referer_module)

    • 【1】valid_referers none | blocked | server_names | string …;定义referer首部的合法可用值; 

      1. none:请求首部没有referer首部

      2. block:请求报文的referer首部没有值

      3. server_names:参数,其值作为主机名或主机名的模式 
        arbitrary_string:直接字符串,可用*匹配 
        regular_expression:被指定正则式匹配到的字符串,~.*.jasonmc.com

    配置示例

    server {
       ……
       location{
           ……
       }

       valid_referers none block server_name *.jasonmc.com jasonmc.* ~\.jasonmc\.;

       if ($invalid_referer) {
           return 403;
       }
    }
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    #客户端测试,伪装referer来源
    curl -k -e "http://www.jasonmc.com" https://10.1.253.29/index.html
    curl -k -e "http://www.baidu.com" https://10.1.253.29/index.html

    总结

    Nginx拥有丰富的扩展,其官网提供了非常全面的介绍。虽说是没有中文,但对于各位英语达人而言……

    【real1】http禁止ip访问(重定向),https禁止ip访问(错误页),全站https

    #http禁止ip访问
    server {
       listen 80;
       server_name localhost;
      #返回404
       error_page 404  /404.html;
       location = /404.html {
          #重写URL
           rewrite /404.html http://www.178linux.com/author/jasonmc permanent;
          #或自定义错误页
           #root /data/blog/error_page/;
       }
      #直接返回301重定向
       #return 302 http://www.google.com;
    }

    #https禁止ip访问
    server {
       listen 443 ssl default_server;
       server_name localhost;
       ssl_certificate /etc/nginx/certs/jasonmc_com.crt;
       ssl_certificate_key /etc/nginx/certs/jasonmc.key;
       error_page 404  /404.html;
       location = /404.html {
           #rewrite /404.html http://www.178linux.com/author/jasonmc permanent;
           root /data/blog/error_page/;
       }
       #return 301 http://www.google.com;
    }

    #基于主机名的虚拟主机,重定向80端口
    server {
       listen 80;
       server_name www.jasonmc.com;
       rewrite ^/(.*)$ https://www.jasonmc.me/$1 permanent;
    }

    #基于主机名的https虚拟主机
    server {
       listen 443 ssl;
       server_name www.jasonmc.com jasonmc.com;
       location / {
           root /data/blog;
           index index.html index.htm;
       }
       ssl on;
       ssl_certificate /etc/nginx/certs/jasonmc_com.crt;
       ssl_certificate_key /etc/nginx/certs/jasonmc.key;
       ssl_session_cache shared:sslcache:10m;

       valid_referers none block server_names *.jasonmc.com jasonmc.* ~\.jasonmc\.;
       if ($invalid_referer) {
       return 403;
       }
    }

    原创文章,作者:helloc,如若转载,请注明出处:http://www.178linux.com/54499

    (0)
    上一篇 2016-10-24 09:12
    下一篇 2016-10-24 10:17

    相关推荐

    • Linux基础之文件管理和bash特性

      部分文件管理命令,bash的一些基础特性,部分glob文件匹配示例

      Linux干货 2018-01-16
    • Memcached + MSM 实现Tomcat Session保持

      Memcached + MSM 实现Tomcat Session保持 tomcat memcached 前言 Memcached介绍 MSM介绍 实验拓扑 实验环境 实验步骤 安装配置Tomcat 安装配置Nginx负载均衡 安装配置Memcached + MSM 总结 前言 上篇文章我们实现了session sticky和session clus…

      2016-04-22
    • 第四周作业

      1、复制/etc/skel目录为/home/tuser1,要求/home/tuser1及其内部文件的属组和其它用户均没有任何访问权限。 [root@wlm ~]# useradd tuser1 [root@wlm ~]# cp -r etc/skel/ /home/tuser1/…

      Linux干货 2016-11-21
    • 学习新技术的10个建议

      我们生活在一个振奋人心的时代。我们可以越来越方便廉价地获得大量学习资源。这些资源的传播载体由最初的教室被变成了博客,技术论坛等。坐拥如此众多的学习资源,我们没有任何理由不去好好利用。随之而来的问题便是如何在这知识的海洋中选择自己的前进方向。在这篇文章中,我将简要概括一些技术学习的建议,希望可以给你带来一些启发。 尽管我的建议主要涉及的是软件开发方面,但是这些…

      Linux干货 2015-03-20
    • N22-第七周作业

      1、创建一个10G分区,并格式为ext4文件系统;    (1) 要求其block大小为2048, 预留空间百分比为2, 卷标为MYDATA, 默认挂载属性包含acl;    (2) 挂载至/data/mydata目录,要求挂载时禁止程序自动运行,且不更新文件的访问时间戳; 创建一个10G的分区:  &nbs…

      Linux干货 2016-12-18
    • linux网络管理

      在 /etc/udev/rules.d/路径下有个70-persistent-ipoib.rules文件,;里边有关于网卡信息的配置,,,在里边可以更改网卡的名字 注意:修改完之后要在/etc/sysconfig/network-scripts/ifcfg-eth0中修改,不然不能使用。 在Centos6以后有一个服务NetworkManager,他可以自动…

      Linux干货 2016-09-06