万字带你搞懂nginx的配置文件

前言

了解nginx配置文件的结构和作用,对我们进行nginx的配置事半功倍,下面我们就开始了解下nginx的配置文件

nginx配置文件

nginx的配置文件在安装目录conf文件夹下,名为nginx.conf。Nginx服务器的基础配置,默认的配置都存放在此。

默认的nginx.conf 内容如下:

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


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

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

nginx配置文件结构

nginx配置文件结构如下:

...              #全局块

events {         #events块
   ...
}

http      #http块
{
    ...   #http全局块
    server        #server块
    { 
        ...       #  server全局块
        location [PATTERN]   #location块
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全局块
}

1、全局块:配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。

2、events块:配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。

3、http块:可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。

4、server块:配置虚拟主机的相关参数,一个http中可以有多个server。

5、location块:配置请求的路由,以及各种页面的处理情况。

下面开始解析各个模块的配置

全局块配置

全局配置主要配置nginx在运行时与具体业务功能(比如http服务或者email服务代理)无关的一些参数,比如工作进程数,运行的身份等。

例:

user  www www;
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
error_log  /data/logs/nginx_error.log  crit;
pid        /usr/local/webserver/nginx/nginx.pid;
worker_rlimit_nofile 65535;

解析:

user www www;: 指定nginx进程使用什么用户启动

worker_processes 4; : 指定启动多少进程来处理请求,一般情况下设置成CPU的核数,如果开启了ssl和gzip更应该设置成与逻辑CPU数量一样甚至为2倍,可以减少I/O操作。使用grep ^processor /proc/cpuinfo | wc -l查看CPU核数。

worker_cpu_affinity 0001 0010 0100 1000;: 在高并发情况下,通过设置将CPU和具体的进程绑定来降低由于多核CPU切换造成的寄存器等现场重建带来的性能损耗。如worker_cpu_affinity 0001 0010 0100 1000; (四核)。

error_log /data/logs/nginx_error.log crit;: error_log是个主模块指令,用来定义全局错误日志文件。日志输出级别有debug、info、notice、warn、error、crit可供选择,其中,debug输出日志最为最详细,而crit输出日志最少。

pid /usr/local/webserver/nginx/nginx.pid;: 指定进程pid文件的位置。

worker_rlimit_nofile 65535;: 用于指定一个nginx进程可以打开的最多文件描述符数目,这里是65535,需要使用命令“ulimit -n 65535”来设置。

events模块

events模块主要配置影响nginx服务器或与用户的网络连接

例:

 events{
  use epoll;
  worker_connections      65536;
}

解析:

use epoll;use是个事件模块指令,用来指定Nginx的工作模式。Nginx支持的工作模式有select、poll、kqueue、epoll、rtsig和/dev/poll。其中select和poll都是标准的工作模式,kqueue和epoll是高效的工作模式,不同的是epoll用在Linux平台上,而kqueue用在BSD系统中。
对于Linux系统,epoll工作模式是首选。在操作系统不支持这些高效模型时才使用select。

worker_connections 65536;每一个worker进程能并发处理(发起)的最大连接数(包含与客户端或后端被代理服务器间等所有连接数)。
nginx作为反向代理服务器,计算公式 最大连接数 = worker_processes * worker_connections/4,所以这里客户端最大连接数是65536,这个可以增到到8192都没关系,看情况而定,但不能超过后面的worker_rlimit_nofile。
当nginx作为http服务器时,计算公式里面是除以2。进程的最大连接数受Linux系统进程的最大打开文件数限制,在执行操作系统命令ulimit -n 65536后worker_connections的设置才能生效。

http模块

可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。

例:

http{
  include       mime.types;
  default_type  application/octet-stream;
  #charset  gb2312;
 }

解析:

include是个主模块指令,实现对配置文件所包含的文件的设定,可以减少主配置文件的复杂度。类似于Apache中的include方法。

default_type属于HTTP核心模块指令,这里设定默认类型为二进制流,也就是当文件类型未定义时使用这种方式,例如在没有配置PHP环境时,Nginx是不予解析的,此时,用浏览器访问PHP文件就会出现下载窗口。

charset gb2312; 指定客户端编码格式。

下面是一些http配置的参数:

server_names_hash_bucket_size 128;: 服务器名字的hash表大小。
client_header_buffer_size 32k;:用来指定来自客户端请求头的header buffer 大小。对于大多数请求,1K的缓存已经足够了,如果自定义了消息头或有更大的cookie,可以增大缓存区大小。
large_client_header_buffers 4 128k;:用来指定客户端请求中较大的消息头的缓存最大数量和大小,4为个数,128k为大小,最大缓存为4个128KB。
client_max_body_size 8m; : 客户端请求的最大的单个文件字节数。
client_max_body_size 10m; : 允许客户端请求的最大单文件字节数。如果有上传较大文件,请设置它的限制值。
client_body_buffer_size 128k;: 缓冲区代理缓冲用户端请求的最大字节数。
sendfile on ; : 开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,减少用户空间到内核空间的上下文切换。对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。开启 tcp_nopush on; 和tcp_nodelay on; 防止网络阻塞。
keepalive_timeout 65 : : 长连接超时时间,单位是秒,这个参数很敏感,涉及浏览器的种类、后端服务器的超时设置、操作系统的设置,可以另外起一片文章了。长连接请求大量小文件的时候,可以减少重建连接的开销,但假如有大文件上传,65s内没上传完成会导致失败。如果设置时间过长,用户又多,长时间保持连接会占用大量资源。
client_body_timeout 60s; : 用于设置客户端请求主体读取超时时间,默认是60s。如果超过这个时间,客户端还没有发送任何数据,nginx将返回Request time out(408)错误。
send_timeout : : 用于指定响应客户端的超时时间。这个超时仅限于两个连接活动之间的时间,如果超过这个时间,客户端没有任何活动,Nginx将会关闭连接。
gzip on;开启gzip压缩输出
gzip_min_length 1k; 最小压缩文件大小,页面字节数从header头的Content-Length中获取。默认值为0,不管多大页面都压缩,建议设置成大于1K的字节数,小于1K可能会越压越大。
gzip_buffers 4 16k; 压缩缓冲区,表示申请四个16K的内存作为压缩结果流缓存,默认是申请与原始数据大小相同的内存空间来存储gzip压缩结果。
gzip_http_version 1.1; 用于设置识别HTTP协议版本,默认是1.1,目前主流浏览器都已成指出。(默认1.1,前端如果是squid2.5请使用1.0)
gzip_comp_level 6; 压缩等级,1压缩比最小,处理速度最快,9压缩比最大,传输速度快,但是消耗CPU资源。

server模块

http服务上支持若干虚拟主机。每个虚拟主机一个对应的server配置项,配置项里面包含该虚拟主机相关的配置。在提供mail服务的代理时,也可以建立若干server。每个server通过监听地址或端口来区分。

下面是server中常用的配置属性

listen:监听的端口,默认为80

server_name:服务器名,如localhost、www.example.com,可以通过正则匹配

root:站点根目录,即网站程序存放目录 

index:查询排序,先查询第一个文件是否存在,再查询第二个,一直查询下去,直到查询到

error_page :错误页面

nginx支持三种类型的 虚拟主机配置

1、基于ip的虚拟主机, (一个主机绑定多个ip地址)

server{
  listen       192.168.1.1:80;
  server_name  localhost;
}
server{
  listen       192.168.1.2:80;
  server_name  localhost;
}

2、基于域名的虚拟主机(servername)

#域名可以有多个,用空格隔开
server{
  listen       80;
  server_name  www.nginx1.com www.nginx2.com;
}
server{
  listen       80;
  server_name  www.nginx3.com;
}

3、基于端口的虚拟主机(listen不写ip的端口模式)

server{
  listen       80;
  server_name  localhost;
}
server{
  listen       81;
  server_name  localhost;
}

location模块

location主要用于某些特定的uri的配置,location的配置只会对匹配的uri生效

语法

location  [=|~|~*|^~] /uri/  {...}

匹配规则:

= : 表示精确的URI匹配,需要与配置的URI相等
~: 表示区分大小写的正则匹配
~*:表示不区分大小写的正则匹配
!~ && !~*:表示区分大小写不匹配的正则和不区分大小写的不匹配的正则
/:通用匹配,任何请求都会匹配到
^~:用于标准 uri 前,并要求一旦匹配到就会立即处理,不再去匹配其他的那些个正则 uri,一般用来匹配目录

location里最常见的两个属性:root和proxy_pass

root

root表示根目录,一般我们静态文件时,使用root指定文件所在的路径

root的处理结果是:root路径+location路径

实例:图片请求转到图片储存的目录

location ~*\.(gif|jpg|jpeg|png)$ {
          root /usr/nginx_data/images;
}

当我们发送一个ip:port/test.jpg请求时,nginx就会去root指定的目录下查找test.jpg文件,如果文件存在则返回文件,如果不存在则返回404

proxy_pass
proxy_pass:反向代理配置,用于代理请求,适用于前后端负载分离或多台机器、服务器负载分离的场景,在匹配到location配置的URL路径后,转发请求到【proxy_pass】配置的URL,是否会附加location配置路径与【proxy_pass】配置的路径后是否有"/“有关,有”/"则不附加。

proxy_pass后面的url加/,表示绝对根路径;如果没有/,表示相对路径,把匹配的路径部分也给代理走。

例:

下面配置都请求http://ip/test/a.html

第一种:proxy_pass配置的URL最后带/,proxy_pass不包含路径(只包含ip和端口)

location /test/ 
{ 
proxy_pass http://127.0.0.1:8080/; 
}

代理到的URL:http://127.0.0.1/a.html

代理结果为:proxy_pass+请求url匹配的location路径后的内容(即不包含匹配的路径)

第二种:proxy_pass配置的URL最后不带/,proxy_pass不包含路径(只包含ip和端口)

location /test/ 
{ 
proxy_pass http://127.0.0.1:8080; 
}

代理到的URL:http://127.0.0.1:8080/test/a.html

代理结果为:proxy_pass替换请求url的ip和端口(包含匹配的路径)

第三种:proxy_pass配置的URL最后带/,proxy_pass包含路径

location /test/ 
{ 
proxy_pass http://127.0.0.1:8080/new/; 
}

代理到的URL:http://127.0.0.1:8080/new/a.html

代理结果为:proxy_pass+请求url匹配的location路径后的内容(即不包含匹配的路径)

第四种:proxy_pass配置的URL最后不带/,proxy_pass包含路径

location /test/ 
{ 
proxy_pass http://127.0.0.1:8080/new; 
}

代理到的URL:http://127.0.0.1:8080/newa.html

代理结果为:proxy_pass+请求url匹配的location路径后的内容(即相当于/test/换成了/new)

nginx配置实例解析

最后附上一个带有注解的nginx配置文件,大家可以参考

########### 每个指令必须有分号结束。#################
#user administrator administrators;  #配置用户或者组,默认为nobody nobody。
#worker_processes 2;  #允许生成的进程数
#pid /nginx/pid/nginx.pid;   #指定nginx进程运行文件存放地址
error_log log/error.log debug;  #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
events {
    accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on
    multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off
    #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大连接数
}
http {
    include       mime.types;   #文件扩展名与文件类型映射表
    default_type  application/octet-stream; #默认文件类型,默认为text/plain
    #access_log off; #取消服务日志    
    log_format myFormat '$remote_addr$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
    access_log log/access.log myFormat;  #combined为日志格式的默认值
    sendfile on;   #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
    sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
    keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块。

    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #backup表示热备
    }
    error_page 404 https://www.baidu.com; #错误页
    server {
        keepalive_requests 120; #单连接请求上限次数。
        listen       4545;   #监听端口
        server_name  127.0.0.1;   #监听地址       
        location  ~*^.+$ {       #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
           #root path;  #根目录
           #index vv.txt;  #设置默认页
           proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表
           deny 127.0.0.1;  #拒绝的ip
           allow 172.18.5.54; #允许的ip           
        } 
    }
}
1. Nginx简介 1.1. 什么是nginx 1.2. Nginx的优点 1.3. 哪里使用到nginx 1.4. Nginx和Apache的区别 2. 安装Nginx服务器 2.1. 在windows上安装 2.2. 在Linux上安装 2.2.1. 写在前面 2.2.2. 准备使用yum安装nginx的运行环境 2.2.3. 安装pcre 2.2.4. 安装zlib库 2.2.5. 安装nginx 2.2.6. 控制nginx 2.2.7. nginx安装服务 3. Nginx配置文件详解 3.1. Nginx的主配置文件概述 3.1.1. 认识配置文件 3.1.2. nginx配置文件结构 3.1.3. nginx的全局配置 3.2. events配置 3.3. http的配置 3.4. nginx重要指令之location 4. nginx中的rewrite 4.1. 什么是rewrite 4.2. rewrite的命令的作用域和优先级 4.3. if指令 4.3.1. if指令的语法 4.3.2. if指令中使用的逻辑运算符 4.3.3. If指令中可以使用的变量 4.3.4. if指令实例 4.4. rewrite指令 4.4.1. rewrite指令语法 4.4.2. flag标记 4.4.3. set指令 4.4.4. return指令 4.4.5. rewrite实例 5. nginx的虚拟主机 5.1. 什么是nginx的虚拟主机 5.2. 标准的虚拟主机配置 5.3. 规划虚拟主机的配置文件 6. 动静分离 7. nginx反向代理 7.1. 什么是反向代理 7.2. 明确两个概念 7.3. 特点 7.4. 反向代理配置 7.5. 可以将代理配置单独放在一个配置文件中 8. nginx负载均衡(自学) 8.1. 什么是负载均衡 8.2. 负载均衡的优点 8.3. 负载均衡的分配策略 8.4. 负载均衡配置 9. 安装PHP 10. PHP-FPM 10.1. 什么是PHP-FPM 10.2. 为什么要是使用PHP-FPM 10.3. 安装并且启动PHP-FPM 10.3.1. 安装 10.3.2. fpm的配置 10.3.3. 启动和停止 10.3.4. 自启动php-fpm 10.3.5. 检查php-fpm是否启动 10.4. nginx使用php-fpm处理php
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值