user nginx;  # 设置启动服务的用户,格式:user username groupname
worker_processes auto;  # 服务器实现并发处理的关键,理论上值越大并发处理量越多,值为数值或auto
error_log /var/log/nginx/error.log error; # 日志存放路径,和错误级别
pid /run/nginx.pid;  #pid文件存放位置

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;  # 加载第三方模块

events {
    worker_connections 1024;  # worker process 同时开启的最大连接数
    accept_mutex on;  # 解决“惊群”问题,防止多个进程对连接进行争抢,默认开启不用写
    multi_accept off;  # 单个 worker process 是否同时接收多个连接请求,默认关闭
    use select;  # 事件驱动模型的选择
}

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  /var/log/nginx/access.log  main; # 定义日志位置和日志格式,关闭用 off

    sendfile            on; # 是否开启传输文件,
    sendfile_max_chunk 128k; # 传输文件的大小
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65; # 连接超时时间,server、location都可以设置
    keepalive_requests 100; # 单个连接请求的上线,默认100
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types; # 引入 types{} 用来识别前端请求的资源类型
    default_type        application/octet-stream; # 配置用于处理前端的MIME类型

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server; # default_server 表示设置为默认服务
        listen       [::]:80 default_server; # ipv6地址
        listen       *:80 | *:8080;
        listen  192.168.1.136; # 监听某个IP的所有端口
        listen       80 backlog=1024; # 最多允许1024个网络连接处于挂起状态
        server_name  _;
        server_name  123.com www.456.com; # 域名之间用空格隔开,默认第一个为主要名称
        server_name  ~www\d+\.myserver\.com$; # 可以使用正则表达式
        server_name  *.myserver.com  www.myserver.* ; 可以使用通配符
        
        listen       80;
        server_name  192.168.1.138; # 基于IP的虚拟主机,和listen一起使用
        
        root         /usr/share/nginx/html; # http、server、location中都可设置,大多数变量也可以用

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        # [=|~|~*|^~] uri {} 
        # 如果正则uri匹配到就用第一个匹配到的正则uri,否者就用匹配度最高的标准uri
        location / {
        # = 严格匹配
        # ~ ~* 表示uri中包含正则,后者不区分大小写
        # ^~ 找到匹配度最高的标准uri后就不匹配正则了
        
        index index.html index.htm $1.html; # 也可使用变量
        }

        error_page 404 /404.html; # http、server、location中都可设置
        error_page 405 =404 http://www.123.com/xxx.html; # 可以是地址或路径
        location = /40x.html { # 重新定向40x.html页面的位置
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
        # 基于IP访问控制,顺序执行
        location / {
            deny 192.168.1.1;
            allow 192.168.1.0/24;
            deny all;
        }
        location / {
            auth_basic "entrt you password"; # 开启写提示符,关闭写off
            auth_basic_user_file path/pwd.txt; # 指定密码文件,格式为:name:password:comment 
            # 密码要加密的话用 htpasswd -c -d path/pwd.txt username 执行一次加一个用户,或用crypt()函数
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}


gzip


ngx_http_gzip_module:

Syntax:gzip on | off;

Default:gzip off;

Context:http, server, location, if in location

location  / {
    gzip on;
    gzip_buffers 32 4k;     # 缓存空间个数 大小k 或 16 8k
    gzip_comp_level 3;      # 压缩级别,9为最高
    gzip_disable regex ...; # 根据特殊浏览器关闭压缩功能
    gzip_http_version 1.1;  # 开启gzip功能的最低http协议版本,不用设置默认即可
    gzip_min_length 1024;   # 开启压缩数据的最小长度
    gzip_proxied off;    # 反向代理时是否对后端返回的内容进行压缩,更多选项详见手册
    gzip_type text/plain text/html; # 对指定的类型开启压缩,默认为 text/html
    gzip_vary off;       # 是否加上 Vary: Accept-Encoding 头部,告诉浏览器数据被压缩过
}

ngx_http_gzip_static_module:

预处理压缩,如果数据此前被压缩过且浏览器支持压缩,就将压缩过的数据返回给客户端。

gzip_static on; # 开启或关闭该模块
# 该模块下的其他指令用法与 ngx_http_gzip_module 相同,除了 gzip_proxied 支持的参数不同

ngx_http_gunzip_module:

对客户端不支持gzip的进行解压后发送给客户端,支持的任然返回压缩数据。

gunzip_static on | off; # 开启或关闭该模块,默认关闭
gunzip_buffers 32 4k | 16 8k; # 解压时使用的空间大小
# 其他指令同 ngx_http_gzip_module

gzip使用过程中的问题处理:

1、关闭不支持gzip压缩功能的浏览器。

gzip_disable "MSIE [1-6]\.";

2、如果 nginx 作为前端开启 gzip 功能,后端的 tomcat 就不要开启gzip 功能了。

3、如果与Squid 3.0之前的版本配合使用要开启静态压缩 ngx_http_gzip_static_module 模块,gzip_static on;


upstream


ngx_http_upstream_module:

upstream backed {
    ip_hash; # 根据请求的IP来固定到一个后端服务器
    least_conn; # 均衡负载组内的服务器,根据权重和连接数
    keepalived 32; # 每个工作进程的缓存中保留的上游服务器的最大空闲keepalive连接数
    server backend.example.com weight=5;
    server 192.168.1.135:8080 max_fails=3 fail_timeout=10s;
    server unix:/tmp/backend;
    sticky cookie srv_id expires=1h domain=.example.com path=/; # 根据cookie来固定到一个服务端
}


rewrite


ngx_http_rewrite_module:

Context:server, location

if ($var){}
if ($request_method = POST){} # 字符串不用加引号
if ($http_user_agent ~ MSIE){} # 使用正则匹配
if ($http_cookie ~* "id=([^;]+)(?:|$)"){} # 使用$1 引用匹配到的值
~   # 正则
~*  # 不区分大小写
!~  # 取反
!~* # 取反不区分大小写

if (-f $request_filename){} # 文件是否存在
!-f # 文件是否不存在
-d  # 目录是否存在
!-d # 目录是否不存在
-e  # 目录或文件是否存在
-x  # 文件是否可执行
!-x # 文件是否不可执行

break;
return 404;   # 返回0-999任意状态码
return hello; # 返回具体内容
return URL;   # 返回具体内容
return 301 URL; # 返回具体内容

rewrite ^(/myweb/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;    # 从写后的URI重新发给server再逐个匹配location
rewrite ^(/myweb/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;   # 使用重写后URI继续执行
rewrite ^(/myweb/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 redirect; # 302 临时重定向
rewrite ^(/myweb/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 permanent;# 301 永久重定向

rewrite_log on | off; # URL重写日志以notice级别输出到error_log中
set $variable value # 设置变量
uninitialized_variable_warn on | off; # 使用未初始化的变量时是否开启警告日志

域名跳转:

server {
    listen 80;
    server_name jump.myweb.name;
    rewrite ^/ http://www.myweb.info/;
}
server {
    listen 80;
    server_name jump.myweb.name;
    if ($host ~ myweb\.info) {
        rewrite ^(.*) http://jump.myweb.name$1 permanent;
    }
}

网站镜像:

server{
    listen 80;
    server_name mirror.myweb.name;
    rewrite ^(.*) http://www.myweb.com$1 last;
}
server{
    location ^~ /source {
        rewrite ^/source(.*) http://www.myweb.com/web$1 last;
        break;
    }
}

独立域名:

server {
    listen 80;
    server_name bbs.myweb.com;
    rewrite ^(.*) http://www.myweb.com/bbs$1 last;
    break;
}

目录自动添加“/”:myweb.com/bbs 重写为 myweb.com/bbs/ ,不加斜线是无法访问二级目录的

server{
    listen 80;
    server_name www.myweb.com;
    location ^~ /bbs {
        rewrite ^/(.*)([^/])$ http://$host/$1/$2/ permanent; 
    }
}

防盗链:

server{
    listen 80;
    server_name www.myweb.com;
    location ~* ^.+\.(gif|jpg|png)${
        valid_referers none blocked server_names *. myweb.com; # 检查这些情况
        if ($invalid_referer){
                rewrite ~/ http://www.myweb.com/forbidden.jpg;
        }
    }
}
server{
    listen 80;
    server_name www.myweb.com;
    location /images/{  # 目录名
        valid_referers none blocked server_names *. myweb.com; # 检查这些情况
        if ($invalid_referer){
                rewrite ~/ http://www.myweb.com/forbidden.jpg;
        }
    }
}


proxy


ngx_http_proxy_module:

正向代理:

resolver 127.0.0.1 [::1]:5353 valid=30s; # DNS服务器ip地址,数据包有效时间
resolver_timeout 10; # DNS解析超时时间
proxy_pass http://$http_host$request_uri; # 代理服务器协议和地址
# 使用实例
server{
    resolver 8.8.8.8;
    listen 82;
    location / {
        proxy_pass http://$http_host$request_uri;
    }
}

反向代理:

proxy_pass http://www.myweb.com/uri; 
proxy_pass http://localhost:8080/uri/; 
proxy_pass http://unix:/tmp/backend.socket:/uri/;

例:

upstream myweb{
    server http://192.168.1.123:8080/uri/; 
    server http://192.168.1.123:8080/uri/; 
    server http://192.168.1.123:8080/uri/; 
}
server {
    listen 80;
    server_name www.myweb.com;
    location /{
        proxy_pass myweb;  # 这里的myweb 不需要加http:,因为在upstream 中已近指明了是http,如果上面没加,这里就要加上http
    }
}
# 注意
proxy_pass 192.168.1.135/uri;  # 包含uri就改变请求的uri,不包含则不改变
location / {
    # 这种情况两个效果一样
    proxy_pass myweb;
    proxy_pass myweb/;
}
location /server/ {
    # 请求的如果是http://myweb.com/server/index.html第二个就会转向 http://myweb/index.html
    proxy_pass myweb;
    proxy_pass myweb/;
}

proxy_hide_header field;    # 设置要隐藏的header头

proxy_pass_header field;    # 设置被代理的头信息是否被发送

proxy_pass_request_headers on | off; # 设置客户端的请求头发送给代理服务器

proxy_set_header field value;    # 修改客户端的请求头后发送给后端服务器

proxy_set_body value;    # 修改客户端的请求体后发送给后端服务器

proxy_bind address;    # 指定某个IP来处理向后端的请求

location /app1/ {
    proxy_bind 127.0.0.1;
    proxy_pass http://example.com/app1/;
}
location /app2/ {
    proxy_bind 127.0.0.2;
    proxy_pass http://example.com/app2/;
}

proxy_connect_timeout 30s;    # 连接后端服务器超时时间

proxy_read_timeout 30s;    # 等待响应的超时时间

proxy_send_timeout 30s;    # 发出send请求后的超时时间

proxy_http_version 1.1;    # 向后端请求的http版本

proxy_method GET | POST;     # 设置向后端请求的方法

proxy_ignore_client_abort on | off;    # 客户端中断请求后,向后端请求是否中断

proxy_ignore_header field;    # 设置后端返回的header头不去处理

proxy_redirect redirect replacement;    # 解决客户端请求地址与后端返回的地址不相同的问题

proxy_redirect http;//location:8080/proxy/ http://myweb/fronted/;  # 改为后者
proxy_redirect off; # 关闭
location /server/ {
    proxy_pass http://myweb/source/;
    proxy_redirect default;  # 表示上面的uri也就是 /source/ 作为replacement
}
location /server/ {
    proxy_pass http://myweb/source/;
    proxy_redirect http://myweb/source/ /server/;
}

proxy_intercept_errors on | off;    # 服务器返回400以上错误时,开启返回nginx错误,关闭返回后端服务器错误

proxy_headers_hash_max_size 512;    # http报文头的哈希表容量

proxy_headers_hash_bucket_size size;    # 服务器名称字符长度

proxy_next_upstream status;    # 在何种情况下将请求发送给下一个服务器

proxy_ssl_session_reuse on | off;    # 是否使用https连接后端服务器


Proxy Buffer


        proxy buffer 缓冲,用来协调传输效率不同的设备,会异步的将数据传输给客户端,且全部数据传输到buffer后才传输给客户端,如果关闭buffer则nginx只要接收到数据就会同步传输给客户端。

proxy_buffering on | off;    # 开启或关闭buffer

proxy_buffers 8 4k | 8k;    # 使用的空间大小

proxy_busy_buffers_size size;    # 设置同时处于BUSY 状态的buffer总数大小

proxy_temp_path path [level1,level2]    # 设置临时存放大文件buffer路径

proxy__max_temp_file_size size;    # 临时文件总体积大小,默认1024M

proxy_temp_file_write_size size;    # 同时写入临时文件的数据总大小,防止IO过载


Proxy Cache


        cache机制依赖于buffer,要开启buffer才能开启cache。

proxy_cache zone | off;    # zone表示用于缓冲的内存区域名称

proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment $http_pragma $http_authorization;    # 不从缓存中获取数据的条件,是and的关系,有一个不为空就不从缓存取

proxy_cache_key $scheme$proxy_host$uri$is_args$args;    # 设置缓存key名称

proxy_cache_lock on | off;    # 多个请求时只能有一个填充某项数据,上锁

proxy_cache_lock_timeout 5s;    # 锁超时时间

proxy_cache_min_uses number;    # 请求多少次后才缓存,默认为1

proxy_cache_path /nginx/cache/a levels=2:2 keys_zone=b:100m;    # 设置缓存路径和缓存索引相关内容,只能在http模块中。

proxy_cache_use_stable error | timeout ....# 后端服务器不能访问时使用缓存返回给客户端,后面的参数是后端服务器处于这些状态时启用该功能,默认off

proxy_cache_valid 200 302 10m;    # 根据不同的响应状态码设置不同的缓存时间

proxy_no_cache string;    # string为变量,当string有值时不使用缓存

proxy_cache on | off | string;    # 另一种缓存方法,对静态数据效果比较好,string为指定的缓存目录,值为on时缓存文件放在 alias或root路径下。

proxy_store_access user:rw group:rw all:r;    # 设置用户或用户组对缓存数据的访问权限



15503052691233_upload.png

15503052694089_upload.png

log_format参考:

http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format

15496015574638_upload.png

15496016091510_upload.png

15496016591489_upload.png