nginx

nginx介绍

官网:http://nginx.org

nginx:engine X,是由1994年毕业于俄罗斯国立莫斯科鲍曼科技大学的同学为俄罗斯rambler.ru公司开发的,开发工作最早从2002年开始,第一次公开发布时间是2004年10月4日,版本号是0.1.0

nginx 是免费,开源,高性能的HTTP和反向代理服务器,邮件代理服务器,通用TCP/UDP代理服务器,解决C10K问题(10K Connections)。

特性:

  模块化设计,较好的扩展性
  高可靠性
  支持热部署:不停机更新配置文件,升级版本,更换日志文件
  低内存消耗:10000个keep-alive连接模式下的非活动连接,仅需2.5M内存
  event-driven,aio,mmap,sendfile

基本功能:

  静态资源的web服务器
  http协议反向代理服务器
  pop3/imap4协议反向代理服务器
  FastCGI(LNMP),uWSGI(python)等协议
  模块化(非DSO),如zip,SSL模块

nginx架构

master/worker结构
  一个master进程:负载加载和分析配置文件、管理worker进程、平滑升级
  一个或多个worker进程,处理并响应用户请求
缓存相关的进程
  cache loader:载入缓存对象
  cache manager:管理缓存对象
模块化
nginx高度模块化,但其模块早期不支持DSO机制;1.9.11版本支持动态装载和卸载
  模块分类:
    核心模块:core module,是 Nginx 服务器正常运行 必不可少 的模块,提供错误日志记录 、配置文件解析 、事件驱动机制 、进程管理等核心功能
  标准模块:
    HTTP 模块: ngx_http_*
      HTTP Core modules 默认功能,提供 HTTP 协议解析相关的功能,比如: 端口配置 、 网页编码设置 、 HTTP响应头设置 等等
      HTTP Optional modules 需编译时指定。可选HTTP模块,主要用于扩展标准的 HTTP 功能,让 Nginx 能处理一些特殊的服务,比如: Flash 多媒体传输 、解析 GeoIP 请求、 网络传输压缩 、 安全协议 SSL 支持等 
    Mail 模块 ngx_mail_*:主要用于支持 Nginx 的 邮件服务 ,包括对 POP3 协议、IMAP 协议和 SMTP协议的支持
     Stream 模块 ngx_stream_*:
  第三方模块:是为了扩展 Nginx 服务器应用,完成开发者自定义功能,比如:Json 支持、 Lua 支持等
 

web服务相关的功能:

虚拟主机(server)
支持 keep-alive 和管道连接( 共享TCP连接发起并发的HTTP请求)
访问日志(支持基于日志缓冲提高其性能)
url rewrite
路径别名
基于IP及用户的访问控制
支持速率限制及并发数限制
重新配置和在线升级而无须中断客户的工作进程
Memcached 的 GET 接口

nginx的安装

官方yum源:
http://nginx.org/packages/centos/7/x86_64/
Fedora-EPEL源:
https://mirrors.aliyun.com/epel/7/x86_64/
编译安装: 
yum install gcc pcre-devel openssl-devel zlib-devel
useradd -r -s /sbin/nologin nginx
./configure --prefix=/apps/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 && make install 

正常运行必备的配置:

user
  指定worker进程的运行身份,如组不指定,默认和用户名同名
pid /PATH/TO/PID_FILE;
  指定存储nginx主进程PID的文件路径
include file | mask;
  指明包含进来的其它配置文件片断
load_module file ;
  模块加载配置文件:/usr/share/nginx/modules/*.conf
  指明要装载的动态模块路径:/usr/lib64/nginx/modules

性能优化相关的配置:

worker_processes number | auto;
  worker进程的数量;通常应该为当前主机的cpu的物理核心数
worker_cpu_affinity auto [cpumask] 提高缓存命中率
  CPU MASK: 00000001:0号CPU
  00000010:1号CPU
  10000000:7号CPU
  例如worker_cpu_affinity 0001 0010 0100 1000;代表绑定第1~4颗cpu。
worker_priority number;
  指定worker进程的nice值,设定worker进程优先级:[-20,19]
worker_rlimit_nofile number;
  所有worker进程能打开的文件数量上限,最好与ulimit -n 的值保持一致,如65535

事件驱动相关的配置:

events {
...
}
worker_connections #;
  每个worker进程所能够打开的最大并发连接数,如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表示每个woker进程可以同时接受所有新的网络连接

调试和定位问题:

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

总结:正常运行必备的配置、性能优化相关的配置、事件驱动相关的配置、调试和定位问题都配置再著配置文件/etc/nginx/nginx.conf,配置如下

user  nginx;

worker_processes  2;
worker_cpu_affinity 01 10;
worker_priority -10;
worker_rlimit_nofile 100000;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

daemon on;
master_process on;
events {
    worker_connections  1024;
    use epoll;
    accept_mutex on;
    multi_accept on;
    
}

上面配置了优先级,以及进程的cpu亲和性,可使用ps命令查看。

http配置

ngx_http_core_module

http协议相关的配置
与套接字相关的配置
定义路径相关的配置
定义客户端请求的相关配置
对客户端进行限制的相关配置
文件操作优化的配置

http协议相关的配置

include /etc/nginx/mime.types;
  在响应报文中将指定的文件扩展名映射至MIME对应的类型
default_type application/octet-stream;
  除上面指定的类型外,就为默认的、MIME类型,浏览器一般会提示下载
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版本

问题一:如何自定义nginx版本信息

如果想自定义响应报文的nginx版本信息,需要修改源码文件,重新编译
如果server_tokens on,修改 src/core/nginx.h 修改第13-14行,如下示例
  #define NGINX_VERSION "1.68.9"
  #define NGINX_VER "nginx/" NGINX_VERSION
如果server_tokens off,修改 src/http/ngx_http_header_filter_module.c
  第49行,如下示例:
  static char ngx_http_server_string[] = "Server: nginx" CRLF;
  把其中的nginx改为自己想要的文字即可,如:testnginx

与套接字相关的配置:

server { ... }
配置一个虚拟主机
server {
    listen address[:PORT]|PORT;
    server_name
    SERVER_NAME;
    root /PATH/TO/DOCUMENT_ROOT;
}
listen PORT|address[:port]|unix:/PATH/TO/SOCKET_FILE
listen address[:port] [default_server] [ssl] [http2 | spdy] [backlog=number][rcvbuf=size] [sndbuf=size];
  default_server;
    设定为默认虚拟主机,无法匹配虚拟主机时使用
  ssl
    限制仅能够通过ssl连接提供服务
  backlog=number 超过并发连接数后,新请求进入后援队列的长度
  rcvbuf=size
    接收缓冲区大小
  sndbuf=size
    发送缓冲区大小
注意:
(1) 基于port;
  listen PORT;
  指令监听在不同的端口
(2) 基于ip的虚拟主机
  listen IP:PORT;
  IP 地址不同
(3) 基于hostname
  server_name fqdn; 指令指向不同的主机名server_name name ...;
虚拟主机的主机名称后可跟多个由空白字符分隔的字符串支持*通配任意长度的任意字符
  server_name *.test.com www.test.*;
支持~起始的字符做正则表达式模式匹配,性能原因慎用
server_name ~^www\d+\.test\.com$;
说明: \d 表示 [0-9]
匹配优先级机制从高到低
  (1) 首先是字符串精确匹配 如:www.test.com
  (2) 左侧*通配符 如:*.test.com
  (3) 右侧*通配符 如:www.test.*
  (4) 正则表达式 如: ~^.*\.test\.com$
  (5) default_server

定义路径相关的配置

root应用于server中
  设置web资源的路径映射;用于指明请求的URL所对应的文档的目录路径,可用于http, server, location, if in location
示例
server {
...
root /data/www/vhost1;
} 
http://www.test.com/images/logo.jpg 
        --> /data/www/vhosts/images/logo.jpg                
location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的所有location,并找出一个最佳匹配,而后应用其配置
示例:
server {...
    server_name www.test.com;
    location /images/ {
        root /data/imgs/;
    }
}
http://www.test.com/images/logo.jpg
    --> /data/imgs/images/logo.jpg    
localtion匹配原则
=   
  对URI做精确匹配必须完全一致才匹配;
^~ 
  对URI的最左边部分做匹配检查,不区分字符大小写
 ~
  对URI做正则表达式模式匹配,区分字符大小写
~*
  对URI做正则表达式模式匹配,不区分字符大小写
不带符号
  匹配起始于此uri的所有的uri
\
转义符,可将 . * ?等转义为普通符号
匹配优先级从高到低:
  =, ^~, ~/~* , 不带符号
root应用于location中
  指定虚拟主机根目录,在定义location时,文件的绝对路径等于 root+location,
示例
server {
    listen 80;
    server_name www.testu.net;
    location / {
        root /data/nginx/html/pc;
        }
    location /about {
    root /opt/nginx/html/pc; 
    #必须要在html目录中创建一个about目录才可以访问,否则报错
    index index.html;
    } 
}        
#生产案例:静态资源配置
location ^~ /static/ { root /data/nginx; } # 或者 location ~* \.(gif|jpg|jpeg|png|bmp|tiff|tif|css|js|ico)$ { root /data/nginx/static; }
alias path;
  路径别名,文档映射的另一种机制;仅能用于location上下文
index file ...;
  指定默认网页文件,此指令由ngx_http_index_module模块提供
error_page code ... [=[response]] uri;
  定义错误页,以指定的响应状态码进行响应可用位置: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 {
}

生产案例

生产案例:
listen 80;
server_name www.test.net;
error_page 500 502 503 504 404 /error.html;
location = /error.html {
  root /data/nginx/html;
}
try_files file ... uri;
try_files file ... =code;
按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如果所有文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向
location /images/ {
  try_files $uri /images/default.jpg;
}
说明:/images/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 100m;
  client_body_buffer_size 2048k;
  client_body_temp_path /apps/nginx/temp 1 2 2; 
 }

对客户端进行限制的相关配置

limit_rate rate;
  限制响应给客户端的传输速率,单位是bytes/second
默认值0表示无限制
  limit_except method ... { ... },仅用于location
限制客户端使用除了指定的请求方法之外的其它方法
  method:GET, HEAD, POST, PUT, DELETE,MKCOL, COPY, MOVE,
  OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, PATCH
limit_except GET {
  allow 192.168.1.0/24;
  deny all;
}
除了GET之外其它方法仅允许192.168.1.0/24网段主机使用

文件操作优化的配置

aio on | off | threads[=pool];
  是否启用aio功能,默认off
directio size | off;
  当文件大于等于给定大小时,同步(直接)写磁盘,而非写缓存,默认off。文件太大就不要放在缓存中了,直接放到磁盘上。
示例:
location /video/ {
    sendfile on;
    aio on;
    directio 8m;
}
open_file_cache off;
open_file_cache max=N [inactive=time];
nginx可以缓存以下三种信息:
  (1) 文件元数据:文件的描述符、文件大小和最近一次的修改时间
  (2) 打开的目录结构
  (3) 没有找到的或者没有权限访问的文件的相关信息
  max=N:可缓存的缓存项上限;达到上限后会使用LRU算法实现管理
  inactive=time:
    缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于open_file_cache_min_uses指令所指定的次数的缓存项即为非活动项,将被删除 
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_access_module

ngx_http_access_module模块可实现基于ip的访问控制功能
allow address | CIDR | unix: | all;
deny address | CIDR | unix: | all;
http, server, location, limit_except
自上而下检查,一旦匹配,将生效,条件严格的置前
示例:
location /about {
  root /data/nginx/html/pc;
  index index.html;
  deny 192.168.1.1;
  allow 192.168.1.0/24;
  allow 10.1.1.0/16;
  allow 2001:0db8::/32;
deny all;
} #先允许小部分,再拒绝大部分

ngx_http_auth_basic_module

ngx_http_auth_basic_module模块
  实现基于用户的访问控制,使用basic机制进行用户认证
auth_basic string | off;
auth_basic_user_file file;
location /admin/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.ngxpasswd;
}
用户口令文件:
1、明文文本:格式name:password:comment
2、加密文本:由htpasswd命令实现
httpd-tools所提供

ngx_http_log_module

log_format name string ...;
  string可以使用nginx核心模块及其它模块内嵌的变量
access_log path [format [buffer=size] [gzip[=level]] [flush=time][if=condition]];
access_log off; #禁用访问日志
  访问日志文件路径,格式及相关的缓冲的配置
  buffer=size
  flush=time 
示例
log_format compression '$remote_addr-$remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" "$gzip_ratio"';

access_log /spool/logs/nginx-access.log compression buffer=32k;

自定义json日志格式

nginx 的默认访问日志记录内容相对比较单一,默认的格式也不方便后期做日志统计分析,生产环境中通常将nginx日志转换为json日志,然后配合使用ELK做日志收集-统计-分析
json格式的访问日志示例:
{"@timestamp":"2019-02-
22T08:55:32+08:00","host":"192.168.7.102","clientip":"192.168.0.1","size":162,"resp
onsetime":0.000,"upstreamtime":"-","upstreamhost":"-
","http_host":"test.net","uri":"/favicon.ico","domain":"www.test.net","xff"
:"-","referer":"-","tcp_xff":"","http_user_agent":"Mozilla/5.0 (Windows NT 6.1;
Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0","status":"404"}
 
log_format access_json '{"@timestamp":"$time_iso8601",'
'"host":"$server_addr",'
'"clientip":"$remote_addr",'
'"size":$body_bytes_sent,'
'"responsetime":$request_time,'
'"upstreamtime":"$upstream_response_time",'
'"upstreamhost":"$upstream_addr",'
'"http_host":"$host",'
'"uri":"$uri",'
'"domain":"$host",'
'"xff":"$http_x_forwarded_for",'
'"referer":"$http_referer",'
'"tcp_xff":"$proxy_protocol_addr",'
'"http_user_agent":"$http_user_agent",'
'"status":"$status"}';
access_log /apps/nginx/logs/access_json.log access_json;

json格式的日志访问统计

#cat nginx_json.py
#!/usr/bin/env python
#coding:utf-8
status_200= []
status_404= []
with open("access_json.log") as f:
for line in f.readlines():
line = eval(line)
if line.get("status") == "200":
status_200.append(line.get)
elif line.get("status") == "404":
status_404.append(line.get)
else:
print("状态码 ERROR")
f.close()
print "状态码200的有--:",len(status_200)
print "状态码404的有--:",len(status_404)
# python nginx_json.py
状态码200的有--: 1910
状态码404的有--: 13ngx_http_log_module

open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];

open_log_file_cache off;

  缓存各日志文件相关的元数据信息
  max:缓存的最大文件描述符数量
  min_uses:在inactive指定的时长内访问大于等于此值方可被当作活动项
  inactive:非活动时长
  valid:验证缓存中各缓存项是否为活动项的时间间隔
 

关于favicon.ico

 favicon.ico 文件是浏览器收藏网址时显示的图标,当使用浏览器访问页面时,浏览器会自己主动发起请求获取页面的favicon.ico文件,但是当浏览器请求的favicon.ico文件不存在时,服务器会记录404日志,而且浏览器也会显示404报错
解决方案:
1、服务器不记录访问日志:
location = /favicon.ico {
  log_not_found off; #文件没发现事件不记录error_log
  access_log off;
            #不记录access_log
}
2、将图标保存到指定目录访问:
#location ~ ^/favicon\.ico$ {
    location = /favicon.ico {
    root /data/nginx/html/pc/images;
}

ngx_http_gzip_module

用gzip方法压缩响应数据,节约带宽
gzip on | off;
  启用或禁用gzip压缩
gzip_comp_level level;
  压缩比由低到高:1 到 9, 默认:1,并不是越高越好,级别越高越消耗CPU,但是带来的压缩比却收益渐渐降低,可设置为5。
gzip_disable regex ...;
  匹配到客户端浏览器不执行压缩
  示例:gzip_disable "MSIE[1-6]\.";
gzip_min_length length;
  启用压缩功能的响应报文大小阈值
gzip_http_version 1.0 | 1.1;
  设定启用压缩功能时,协议的最小版本,默认:1.1
gzip_buffers number size;
  支持实现压缩功能时缓冲区数量及每个缓存区的大小
  默认:32 4k 或 16 8k
gzip_types mime-type ...;
  指明仅对哪些类型的资源执行压缩操作;即压缩过滤器
  默认包含有text/html,不用显示指定,否则出错
gzip_vary on | off;
  如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”
gzip_proxied off | expired | no-cache | no-store | private |no_last_modified | no_etag | auth | any ...;
  nginx充当代理服务器时,对于后端服务器的响应报文,在何种条件下启用压缩功能
  off:不启用压缩
  expired,no-cache, no-store,private:对后端服务器的响应报文首部
  Cache-Control值任何一个,启用压缩功能
示例:
gzip on;
gzip_comp_level 6;
gzip_min_length 64;
gzip_vary on;
gzip_types text/xml text/css application/javascript;

 

ngx_http_ssl_module

ssl on | off;
  为指定虚拟机启用HTTPS protocol, 建议用listen指令代替
ssl_certificate file;
  当前虚拟主机使用PEM格式的证书文件
ssl_certificate_key file;
  当前虚拟主机上与其证书匹配的私钥文件
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
  支持ssl协议版本,默认为后三个
ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
  none: 通知客户端支持ssl session cache,但实际不支持
  builtin[:size]:使用OpenSSL内建缓存,为每worker进程私有
  [shared:name:size]:在各worker之间使用一个共享的缓存ngx_http_ssl_module
ssl_session_timeout time;
  客户端连接可以复用ssl session cache中缓存的有效时长,默认5m
示例:
server {
listen 443 ssl;
server_name www.ssltest.com;
root /app/ssl/htdocs;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
}

ngx_http_rewrite_module

将用户请求的URI基于PCRE regex所描述的模式进行检查,而后完成重定向替换.
if (condition) { ... }
  条件满足时,执行配置块中的配置指令;server, location
condition:
比较操作符:
  = 相同 != 不同
  ~模式匹配,区分字符大小写
  ~*模式匹配,不区分字符大小写
  !~模式不匹配,区分字符大小写
!~* 模式不匹配,不区分字符大小写
文件及目录存在性判断:
  -e,!-e 存在与否(包括文件,目录,软链接)
  -f,!-f 文件 -d,!-d 目录 -x,!-x 执行
注意: if (condition) { ... } 语句中,如果$变量的值为空字符串或是以0开头的任意字符串,则 if 指令认为该条件为false,其它条件为true
return
  return code [text]; #返回客户端指定的状态码和文本说明
  return code URL;
  return URL;
停止处理,并返回给客户端指定的响应码(包括: 204, 400, 402 — 406, 408,410, 411, 413, 416, 500 — 504),并对 301, 302, 303, 307, 308跳 转 到 URL
rewrite_log on | off;
  是否开启重写日志, 发送至error_log(notice level)
set $variable value;
  用户自定义变量
  注意:变量定义和调用都要以$开头
rewrite regex replacement [flag]
  将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为
  replacement指定的新的URI
    注意:如果在同一级配置块中存在多个rewrite规则,那么会自下而下逐个检查;被某条件规则替换完成后,会重新一轮的替换检查。
    隐含有循环机制,但不超过10次;如果超过,提示500响应码,[flag]所表示的标志位用于控制此循环机制。
    如果replacement是以http://或https://开头,则替换结果会直接以重向返回给客户端, 即永久重定向301。 
  [flag]:
    last:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后对新的URI启动新一轮重写检查;提前重启新一轮循环
    break:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块后的其它配置;结束循环。
    redirect:临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;可使用相对路径,或http://或https://开头,此重定向信息不可缓存,状态码:302
    permanent:重写完成后以永久重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求,此重定向信息可缓存,状态码:301

rewrite 生产案例

要求:将 http:// 请求跳转到 https://
location / {
if ($scheme = http ) {  
rewrite / https://www.ssltest.com/ redirect;
}
}
要求:当用户访问到公司网站的时输入了一个错误的URL,可以将用户重定向至官网首页
location / {
root /data/app/html/pc;
index index.html;
if (!-f $request_filename) { 
rewrite (.*) https://www.ssltest.com/index.html;
}
}

ngx_http_referer_module

用来阻止Referer首部无有效值的请求访问,可防止盗链。
valid_referers none|blocked|server_names|string ...;
定义referer首部的合法可用值,不能匹配的将是非法值
  none:请求报文首部没有referer首部
  blocked:请求报文有referer首部,但无有效值
  server_names:referer首部中包含本主机名
  arbitrary_string:任意字符串,但可使用*作通配符
  regular expression:被指定的正则表达式模式匹配到的字符串,要使用~开头,
例如: ~.*\.test\.com

防止盗链生产案例:

valid_referers none block server_names ~\.google\. ~\.baidu\.;
if ($invalid_referer) {
  return 403 "Forbidden Access";
}

配置文件

1、/etc/nginx/conf.d/ssl.conf:用来测试nginx的https通信的配置

server {

    listen 443 ssl;
    server_name www.ssltest.com;
    root /data/app/ssl/htdocs/;
    index index.html;
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key  /etc/nginx/ssl/nginx.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
}

2、/etc/nginx/conf.d/server.conf:

log_format access_json '{"@timestamp":"$time_iso8601",'
'"host":"$server_addr",'
'"clientip":"$remote_addr",'
'"size":$body_bytes_sent,'
'"responsetime":$request_time,'
'"upstreamtime":"$upstream_response_time",'
'"upstreamhost":"$upstream_addr",'
'"http_host":"$host",'
'"uri":"$uri",'
'"domain":"$host",'
'"xff":"$http_x_forwarded_for",'
'"referer":"$http_referer",'
'"tcp_xff":"$proxy_protocol_addr",'
'"http_user_agent":"$http_user_agent",'
'"status":"$status"}';

gzip on;
gzip_comp_level 6;
gzip_min_length 64;
gzip_vary on;
gzip_types text/xml text/css application/javascript;

access_log /data/app/nginx/logs/access_json.log access_json;

server_tokens off;

server {
    listen 80;
    server_name www.testnginx.com;
    error_page 404 =200   /404.html;

    valid_referers none block server_names  ~\.google\. ~\.baidu\.;
    if ($invalid_referer) {
        return 403 "Forbidden Access";
    }

    location = /404.html {
        root /data/app/error;
    }
    
        location / {
        if ($scheme = http ) {
            rewrite / https://www.ssltest.com/ redirect;
            }
        }    
    

#静态资源定义示例
    location ~* \.(gif|jpg|jpeg|png|bmp|tiff|tif|css|js|ico)$ {
        root /data/app/static;
        index index.html;
    }
}
    

3、/etc/nginx/nginx.conf

user  nginx;
worker_processes  2;
worker_cpu_affinity 01 10;
worker_priority -10;
worker_rlimit_nofile 100000;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

daemon on;
master_process on;
events {
    worker_connections  1024;
    use epoll;
    accept_mutex on;
    multi_accept on;
    
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

 

 

 

 
 
 
 

posted on 2020-08-29 14:54  HowOldAreYou  阅读(273)  评论(0编辑  收藏  举报

导航