nginx的配置

通用语法

  • 块配置项由一个块配置项和一对大括号组成,块配置项可嵌套。
  • 配置项的语法格式:配置项名 配置项值1 配置项值2;
  • 在一行前面加"#"表示注释
  • 配置项的单位
    指定空间大小
    K或者k千字节(KB)
    M或者m千字节(MB) 指定时间
    ms(毫秒)
    s(秒)
    m(分钟)
    h(小时)
    d(天)
    w(周,包含7天)
    M(月,包含30天)
    y(年,包含365天)

基本配置

  • 用于调试进程、定位问题的配置项

    • daemon on | off; 是否以守护进程方式运行nginx,默认是
    • master_process on | off; 是否以master/worker方式工作,默认是
    • error_log /path/file level; error日志设置
      • /path/file参数可以是一个具体的文件,默认为logs/error.log文件
      • /path/file可以是/dev/null,这是关闭error日志的唯一手段
      • /path/file可以是stderr,这样日志会输出到标准错误文件中
      • level是日志的输出级别,取值范围:debug、info、notice、warn、error、crit、alert、emerg
      • 当设定为一个级别时,大于或等于该级别的日志都会被输出到/path/file文件中,小于该级别的日志则不会输出
      • 如果日志级别设定到debug,必须在configure时加入--with-debug配置项
    • debug_points [stop | abort]; 是否处理几个特殊的调试点(通常不会使用这个配置项)
    • debug_connection [IP | CIDR]; 仅对指定的客户端输出debug级别的日志
      • 这个配置项属于事件类配置项,必须放在events {...}中才有效
      • 使用debug_connection前,必须在configure时加入--with-debug配置项
    • worker_rlimit_core size; 限制coredump核心转储文件的大小
    • working_directory path; 指定coredump文件生成目录
      • 需确保worker进程有权限向working_directory指定的目录中写入文件
  • 正常运行的配置项
    • env VAR|VAR=VALUE; 定义环境变量
    • include /path/file; 嵌入其他配置文件
    • pid path/file; pid文件的路径,默认为pid logs/nginx.pid;
    • user username [groupname]; nginx worker进程运行的用户及用户组,默认为user nobody nobody;
    • worker_rlimit_nofile limit; 指定nginx worker进程可以打开的最大句柄描述符个数
    • worker_rlimit_sigpending limit; 限制信号队列
  • 优化性能的配置项
    • worker_processes number; nginx worker进程个数,默认为worker_processes 1

      • 模块间确认不会出现阻塞式的调用,则有多少CPU内核就应该配置多少个进程(内核个数可以通过命令cat /proc/stat查看stat文件)
      • 模块间确认会出现阻塞式的调用,则根据需要配置稍多一些的worker进程
    • worker_cpu_affinity cpumask [cpumask...] 绑定nginx worker进程到指定的cpu内核
      • 2核是 01,四核是0001,8核是00000001,有多少个核,就有几位数,1表示该内核开启,0表示该内核关闭。
      • worker_processes最多开启8个,8个以上性能提升不会再提升了,而且稳定性变得更低,所以8个进程够用了。
      2核CPU开8进程,那么可以写为:
      worker_processes 8;
      worker_cpu_affinity 01 10 01 10 01 10 01 10;
    • ssl_engine device; SSL硬件加速
      • 需确保服务器上有SSL硬件加速设备,通过命令openssl engine -t查看是否有SSL硬件加速设备
    • timer_resolution t; 系统调用gettimeofday的执行频率(一般不用配置)
    • worker_priority nice; nginx worker进程优先级设置,默认为worker_priority=0;
      • nice值是进程的静态优先级,取值范围是-20~+19,-20是最高优先级
      • 不建议把worker进程的nice值设置比内核进程的nice值(通常为-5)小
  • 事件类配置项
    • accept_mutex [on | off]; 是否打开accept(负载均衡)锁,默认为accept_mutex on;
    • lock_file path/file; lock文件的路径,默认为lock_file logs/nginx.lock;
      • 打开accept锁并且nginx不支持原子锁,lock_file配置才会生效
    • accept_mutex_delay Nms; 使用accept锁后到真正建立连接之间的延迟时间,默认为accept_mutex_delay 500ms;cept off;
    • use [kqueue | rtsig | epoll | /dev/poll | select | poll | even
    • multi_accept [on | off]; 批量建立新连接,默认为multi_actport]; 选择事件模型,默认nginx会自动使用最合适的事件模型
    • worker_connections number; 每个worker的最大连接数
          从用户的角度,http 1.1协议下,由于浏览器默认使用两个并发连接,因此计算方法:
    nginx作为http服务器的时候:max_clients = worker_processes * worker_connections/2
    nginx作为反向代理服务器的时候:max_clients = worker_processes * worker_connections/4

静态web服务器的配置项

  • 虚拟主机与请求的分发

    • listen address:port [ default | default_server | backlog=num | rcvbuf=size | sndbuf=size | accept_filter=filter | deferred | bind | ipv6only=[on | off] | ssl]; 监听端口,直属于server块,默认listen 80;

      • default、default_server:将所在的server块作为整个web服务的默认server块;默认将nginx.conf中找到的第一个server块作为默认server块
      • backlog=num:表示TCP中backlog队列的大小,默认为-1(不予设置)
      • rcvbuf=size:设置监听句柄的SO_RCVBUF参数
      • sndbuf=size:设置监听句柄的SO_SNDBUF参数
      • accept_filter:设置accept过滤器,只对FreeBSD操作系统有用
      • deferred:当请求数据来临时,worker进程才会开始处理这个连接
      • bind:绑定当前端口/地址对,只有同时对一个端口监听多个地址时才会生效
      • ssl:在当前监听的端口上建立的连接必须基于SSL协议
    • server_name name [...]; 主机名称,直属于server块,默认server_name "";
      • server_name后可以跟多个主机名称
      • server_name与host的匹配优先级
        • 首先选择所有字符串完全匹配的server_name,如www.testweb.com
        • 其次选择通配符在前面的server_name,如*.testweb.com
        • 再次选择通配符在后面的server_name,如www.testweb.*
        • 最后选择使用正则表达式才匹配的server_name,如~^\.testweb\.com$
      • server_name与host不匹配
        • 优先选择在listen配置项后加入[default | default_server]的server块
        • 找到匹配listen端口的第一个server块
    • server_names_hash_bucket_size size; 每个散列桶占用的内存大小,直属于http、server、location,默认serveer_names_hash_bucket_size 32|64|128;
    • server_names_hash_max_size size; 散列表的冲突率,直属于http、server、location,默认server_names_hash_max_size 512;
    • server_name_in_redirect on | off; 重定向主机名称的处理,直属于http、server、location,默认server_name_in_redirect on;
      • 本配置需要配合server_name使用
    • location [=||*|^~|@] /uri/ {...} 根据用户请求中的URI来匹配/uri/表达式,直属于server
      • = 表示把URI作为字符串,以便与参数中的uri做完全匹配
      • ~ 表示匹配URI时是字母大小写敏感
      • ~* 表示匹配URI忽略字母大小写问题
      • ^~ 表示匹配URI时只需要其前半部分与uri参数匹配即可
      • @ 表示仅用于nginx服务内部请求之间的重定向,带有@的location不直接处理用户请求
      • 如果需要表达“如果不匹配...则...”,可以在最后一个location中使用/作为参数,它会匹配所有的http请求,这样就可以表示如果不能匹配前面的所有location,则有“/”这个location处理
  • 文件路径的定义
    • root path; 以root方式设置资源路径,直属于http、server、location、if,默认root html;
    • alias path; 以alias方式设置资源路径,直属于location
      • root和alias区别在于是否会根据完整的URI请求来映射
    • index file; 访问首页,直属于http、server、location,默认index index.html
    • error_page code [code...] [= | =answer-code] uri | @named_location; 根据http返回码重定向页面,直属于http、server、location、if
    • recursive_error_pages [on | off]; 是否允许递归使用error_page,直属于http、server、location,默认recursive_error_pages off;
    • try_files path1 [path2...] uri; 如果所有path都找不到有效的文件,就重定向到最后的参数uri上,直属于server、location
  • 内存及磁盘资源的分配
    • client_body_in_file_only on | clean | off; http包体只存储到磁盘文件中,直属于http、server、location,默认client_body_in_file_only off;

      • 该配置一般用于调试、定位问题
    • client_body_in_single_buffer on | off; http包体尽量写入到一个内存buffer中,直属于http、server、location,默认client_body_in_single_buffer off;
    • client_body_buffer_size size; 存储http包体的内存buffer大小,直属于http、server、location,默认client_body_buffer_size 8k/16k;
    • client_body_temp_path dir_path [level1 [level2[level 3]]]; http包体的临时存放目录,直属于http、server、location,默认client_body_temp_path client_body_temp;
      • [level1 [level2[level 3]]]是为了防止一个目录下的文件数量太多,按照临时文件名最多再加三层目录
    • client_header_buffer_size size; 存储http头部的内存buffer大小,直属于http、server,默认client_header_buffer_size 1k;
    • large_client_header_buffers number size; 存储超大http头部的内存buffer大小,直属于http、server,默认large_client_header_buffers 4 8k;
    • connection_pool_size size; 指定tcp连接的内存池的初始大小,直属于http、server,默认connection_pool_size 256;
    • request_pool_size size; 指定http请求的内存池的初始大小,直属于http、server,默认request_pool_size 4k;
  • 网络连接的设置
    • client_header_timeout time; 读取http头部的超时时间,直属于http、server、location,默认client_header_timeout 60;(默认单位:秒)
    • client_body_timeout time; 读取http包体的超时时间,直属于http、server、location,默认client_body_timeout 60;(默认单位:秒)
    • send_timeout time; 发送响应的超时时间,直属于http、server、location,默认send_timeout 60;(默认单位:秒)
    • reset_timeout_connection on | off; 连接超时后将通过向客户端发送RST包来直接重置连接,直属于http、server、location,默认reset_timeout_connection off;
    • lingering_close off | on | always; 控制nginx关闭用户连接的方式,直属于http、server、location,默认lingering_close on;
    • lingering_time time; 控制nginx关闭用户连接的时间,直属于http、server、location,默认lingering_time 30s;
    • lingering_timeout time; 控制nginx关闭用户连接的时间,直属于http、server、location,默认lingering_timeout 5s;
    • keepalive_disable [msie6 | safari | none]; 对某些浏览器禁用keepalive功能,直属于http、server、location,默认keepalive_disable msie6 safari;
    • keepalive_timeout time; keepalive超时时间,直属于http、server、location,默认keepalive_timeout 75;(默认单位:秒)
    • keepalive_request n; 一个keepalive长连接上允许承载的请求最大数,直属于http、server、location,默认keepalive_request 100;(默认单位:秒)
    • tcp_nodelay on | off; 确认对keepalive连接是否使用TCP_NODELAY选项,直属于http、server、location,默认tcp_nodelay on;
    • tcp_nopush on | off; 在打开sendfile选项时,确定是否开启FreeBSD系统上的TCP_NOPUSH或Linux系统上的TCP_CORK功能,直属于http、server、location,默认tcp_nopush off;
  • MIME类型的设置
    • type {...} MIME type与文件扩展的映射,直属于http、server、location
    • default_type MIME-type; 默认MIME type,直属于http、server、location,默认default_type text/plain;
    • types_hash_bucket_size size; 设置每个散列桶占用的内存大小,直属于http、server、location,默认types_hash_bucket_size 32|64|128;
    • types_hash_max_size size; 散列表的冲突率,直属于http、server、location,默认types_hash_max_size 1024;
  • 对客户端请求的限制
    • limit_except method ... {...} 按http方法名限制用户请求,直属于http
    • client_max_body_size size; http请求包体的最大值,直属于http、server、location,默认client_max_body_size 1m;
      • 用于限制Content-Length所示值的大小的,非常有用处
    • limit_rate speed; 对请求的限速,直属于http、server、location、if,默认limit_rate 0;
    • limit_rate_after time; nginx向客户端发送的响应长度超过limit_rate_after后才开始限速,直属于http、server、location、if,默认limit_rate_after 1m;
  • 文件操作的优化
    • sendfile on | off; sendfile系统调用,直属于http、server、location,默认sendfile系统调用
    • aio on | off; AIO系统调用,直属于http、server、location,默认aio off;
      • 该配置与sendfile功能互斥
    • directio size | off; 使用O_DIRECT选项去读取文件,缓冲区大小为size,直属于http、server、location,默认directio off;
      • 该配置通常对大文件的读取速度有优化作用
      • 该配置与sendfile功能互斥
    • directio_alignment size; 指定以O_DIRECT选项去读取文件时的对其方式,直属于http、server、location,默认directio_alignment 512;
      • 该配置与directio配合使用
    • open_file_cache max=N [inactive=time] | off; 打开文件缓存,直属于http、server、location,默认open_file_cache off;
      • max:表示在内存中存储元素的最大个数
      • inactive:表示在inactive指定的时间段内没有被访问过的元素将会被淘汰,默认时间为60秒
      • off:关闭缓存功能
    • open_file_cache_errors on | off; 是否缓存打开文件错误的信息,直属于http、server、location,默认open_file_cache_errors off;
    • open_file_cache_min_uses number; 不被淘汰的最小访问次数,直属于http、server、location,默认open_file_cache_min_uses 1;
    • open_file_cache_valid time; 检验缓存中元素有效性的频率,直属于http、server、location,默认open_file_cache_valid 60s;
  • 对客户端请求的特殊处理
    • ignore_invalid_headers on | off; 忽略不合法的http头部,直属于http、server,默认ignore_invalid_headers on;
    • underscores_in_headers on | off; http头部是否允许下画线,直属于http、server,默认underscores_in_headers off;
    • If-Modified-Since [off | exact | before]; 对If-Modified-Since头部的处理策略,直属于http、server、location,默认If-Modified-Since exact;
    • merge_slashes on | off; 是否合并相邻的"/",直属于http、server、location,默认merge_slashes on;
    • resolver address ...; 设置DNS名字解析服务器的地址
    • resolver_timeout time; 设置DNS解析的超时时间,直属于http、server、location,默认resolver_timeout 30s;
    • server_tokens on | off; 返回错误页面时是否在server中注明nginx版本,直属于http、server、location,默认server_tokens on;
  • ngx_http_core_module模块提供的变量
    • $arg_PARAMETER:http请求中某个参数的值,如/index.html?size=100,可以用$arg_size取得100这个值
    • $args:http请求中的完整参数。例如,在请求/index.html?_w=120&_h=120中,$args表示字符串_w=120&_h=120
    • $binary_remote_addr:二进制格式的客户端地址。例如:\x0A\xE0B\x0E
    • $body_bytes_sent:表示在向客户端发送的http响应中,包体部分的字节数
    • $content_length:表示客户端请求头部中的Content-Length字段
    • $content_type:表示客户端请求头部中的Content-Type字段
    • $cookie_COOKIE:表示在客户端请求头部中的cookie字段
    • $document_root:表示当前请求所使用的root配置项的值
    • $uri:表示当前请求的URI,不带任何参数
    • $document_uri:与$uri含义相同
    • $request_uri:表示客户端发来的原始请求URI,带完整的参数
    • $host:表示客户端请求头部中的Host字段
    • $hostname:表示nginx所在机器的名称
    • $http_HEADER:表示当前http请求中相应头部的值,HEADER名称全小写。例如,$http_host:表示请求头部对应的值
    • $sent_http_HEADER:表示返回客户端的http响应中相应头部的值,HEADER名称全小写。例如,$sent_http_content_type表示响应中Content-Type头部对应的值
    • $is_args:表示请求中的URI是否带参数,如果带参数,$is_args值为?,如果不带参数,则是空字符串
    • $limit_rate:表示当前连接的限速是多少,0表示无限速
    • $nginx_version:表示当前nginx的版本号
    • $query_string:请求URI中的参数
    • $remote_addr:表示客户端的地址
    • $remote_port:表示客户端连接使用的端口
    • $remote_user:表示使用Auth Basic Module时定义的用户名
    • $request_filename:表示用户请求中的URI经过root或者alias转换后的文件路径
    • $request_body:表示http请求中的包体,该参数只在proxy_pass或fastcgi_pass中有意义
    • $request_body_file:表示http请求中的包体存储的临时文件名
    • $request_completion:表示请求是否已经全部完成
    • $request_method:表示http请求的方法名,如GET、PUT、POST等
    • $scheme:表示http scheme,如在请求https://nginx.com/中表示https
    • $server_addr:表示服务器地址
    • $server_name:表示服务器名称
    • $server_port:表示服务器端口
    • $server_protocol:表示服务器向客户端发送响应的协议,如HTTP/1.1或者HTTP/1.0

反向代理服务器的配置项

  • 负载均衡的基本配置

    • upstream name {...} upstream块定义了一个上游服务器的集群,便于反向代理中的proxy_pass使用,直属于http
    upstream backend {
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
    }
    server {
    location / {
    proxy_pass http://backend;
    }
    }
    • server name [parameters]; 指定一台上有服务器的名字(域名、IP地址端口、UNIX句柄等),直属于upstream

      • parameters可为weight=number:设置向这台上游服务器转发的权重,weigh和ip_hash配置不可同时使用,默认为1
      • parameters可为max_fails=number:向上游服务器转发失败最大次数,该选项与fail_timeout配合使用
      • parameters可为fail_timeout=time:该时间段内转发失败多少次后就认为上游服务器暂时不可用,用于优化反向代理功能。默认为10秒
      • down:表示所在的上游服务器永久下线,只在使用ip_hash配置项时才有用
      • backup:表示上游服务器是备份服务器,在使用ip_hash配置项时无效
      upstream backend {
      server backend1.example.com weight=5;
      server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
      server unix:/tmp/backend3;
      }
    • ip_hash; 可确保同一个客户端的请求只会转发到指定的上游服务器中,直属于upstream
    upstream backend {
    ip_hash;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com down;
    server backend4.example.com;
    }
    • 记录日志时支持的变量

      • $upstream_addr 处理请求的上游服务器地址
      • $upstream_cache_status 表示是否命中缓存,取值范围:MISS、EXPIRED、UPDATING、STALE、HIT
      • $upstream_status 上游服务器返回的响应中的HTTP响应码
      • $upstream_response_time 上游服务器的响应时间,精度到毫秒
      • $upstream_http_$HEADER HTTP的头部,如$upstream_http_host
          log_format timing '$remote_addr - $remote_user [$time_local] $request '
      'upstream_response_time $upstream_response_time'
      'msec $msec request_time $request_time';
          log_format up_head '$remote_addr - $remote_user [$time_local] $request '
      'upstream_http_content_type $upstream_http_content_type';
  • 反向代理的基本配置
    • proxy_pass URL; 将当前请求反向代理到URL参数指定的服务器上,URL可以是主机名、IP地址加端口的形式、Unix句柄,直属于location、if
    • 默认情况下反向代理不会转发请求中的host头部的,如果需要转发,那么必须加上配置:proxy_set_header Host $host;
    • proxy_method method; 转发时的协议方法名,直属于http、server、location,例如:proxy_method POST;
    • proxy_hide_header the_header; 将上游服务器的响应转发给客户端,直属于http、server、location
    • proxy_pass_header the_header; 将原来禁止转发的header设置为允许转发,直属于http、server、location
    • proxy_pass_request_body on | off; 确定是否向上游服务器发送HTTP包体部分,直属于http、server、location,默认proxy_pass_request_body on;
    • proxy_pass_request_headers on | off; 确定是否转发HTTP头部,直属于http、server、location,默认proxy_pass_request_headers on;
    • proxy_redirect [default | off | redirect replacement] 当上游服务器返回的响应是重定向或刷新请求时,重设HTTP头部的location或者refresh字段,直属于http、server、location,默认proxy_redirect default;
    • proxy_next_upstream [error | timeout | invalid_header | http_500 | http_502 | http_503 | http_504 | http_404 | off]; 表示当向一台上游服务器转发请求出现错误时,继续换一台上游服务器处理这个请求,直属于http、server、location,默认proxy_next_upstream error timeout;

最新文章

  1. eclipse导入android项目红叉和红色感叹号怎么解决
  2. NetworkError: 404 Not Found - http://www.companyName.com/Content/fonts/ubuntu-regular-webfont.woff2
  3. Gprinter热敏打印机光栅位图点阵数据解析工具
  4. oracle 锁的介绍 (转)
  5. 创建与删除SQL约束或字段约束
  6. poj2762 强连通+拓扑序
  7. Selenium Tutorial (2) - Selenium IDE In Depth
  8. [反汇编练习]160个CrackMe之001
  9. poj1054The Troublesome Frog
  10. ASP.NET MVC Json() 处理大数据异常解决方法 json MaxJsonLength
  11. int 转换成 CString(VC2008里有这个问题)
  12. C/C++头文件
  13. Struts2之OGNL表达式
  14. The Nerd Factor SPOJ - MYQ5
  15. mybatis简单搭建
  16. angular开发环境搭建及新建项目
  17. JavaScript 的正则也有单行模式了
  18. Scrapy爬取猫眼《复仇者联盟4终局之战》影评
  19. Django model操作
  20. web版ssh的使用

热门文章

  1. Hibernate(4)简单的HelloWorld
  2. flask之信号和mateclass元类
  3. BLEU (Bilingual Evaluation Understudy)
  4. Jetpack 架构组件 Paging 分页加载 MD
  5. java-Freemarker TemplateLoader实现模版
  6. Java程序猿怎样高速理解Kubernetes
  7. ACC自适应巡航控制系统介绍
  8. ECharts JS应用:图表页面实现
  9. jQuery on()方法使用
  10. HashTable代码解析