Nginx中 配置文件 nginx.conf 详解

1. nginx.conf 文件配置结构

在这里插入图片描述
从图中可看出主要包含三大块:全局块、event块、http块 { 包含:http全局块 和 server块( server全局块 和 location块 ) }。

...              	# 全局块

events {
    
             	# events块
   ...
}

http {
    
    							# http块
    ...   						# http全局块
    server {
    
     					# server块
        ...       				# server全局块
        location [PATTERN] {
    
     	# location块
            ...
        }
        location [PATTERN] {
    
    
            ...
        }
    }
    server {
    
     
        ...      
    }
    ...				# http全局块
}
  • 全局块: 配置影响 nginx 全局的指令。一般有运行 nginx 服务器的用户组、nginx 进程 pid 存放路径、日志存放路径、配置文件引入、允许生成 worker process 数等;
  • Events 块: 配置影响 nginx 服务器或与用户的网络连接。有每个进程的最大连接数、选取哪种事件驱动模型处理连接请求、是否允许同时接受多个网路连接、开启多个网络连接序列化等;
  • Http 块: 可以嵌套多个 server、配置代理、缓存、日志定义等绝大多数功能和第三方模块的配置。如:文件引入、mime-type 定义、日志自定义、是否使用 sendfile 传输文件、连接超时时间、单连接请求数等;
  • Server 块: 配置虚拟主机的相关参数,一个 http 中可以有多个 server;
  • Location 块: 配置请求的路由,以及各种页面的处理情况;

注意: Nginx 配置的注释是以 # 开头,并且每条语句都以 ; 结束,除了语句块 {}。

2. 配置详解

全局块

所有在 nginx.conf 内但不在任何 { } 中的指令都属于全局块的指令:

# 用户组
user myUsr myGroup;

# 工作进程数
worker_processes  1;

# 进程文件路径
pid /user/local/nginx/nginx.pid;

# 日志路径和日志级别
error_log logs/error.log debug;

指令详解:

  • 用户或用户组默认为 nobody( 如果配置为 user nobody nobody, 则所有用户都能启动 nginx 进程 );
  • 工作进程数可设置为CPU的核心数(如果设置 auto, 则 nginx 将进行自动检测设置好之后,可通过 ps -ef | grep nginx 查看进程的启动情况);
  • 日志级别有:debug | info | notice | warn | error | crit | alert | emerg;

注意: Nginx 配置中,以 / 开头的路径表示绝对路径,不以 / 开头的路径表示相对路径,相对路径的根目录为 Nginx 的根目录。

Events 块

所有写在 events{} 中的指令都属于 Events 块指令:

events {
    
    
	# 设置网路连接序列化
	accept_mutex on;
	
	# 一个进程是否同时接受多个网络连接
	multi_accept on;
	
	# 事件驱动模型
	use epoll;
	
	# 最大连接数
	worker_connections  1024;
}

指令详解:

  • 设置网路连接序列化是为了防止惊群现象发生,默认为 on;
  • 是否同时接受多个网络连接指令默认值为 off;
  • 事件驱动模型的可选项有:select | poll | kqueue | epoll | resig | /dev/poll | eventport;

HTTP 全局块

所有写在 http{ } 块中,但不写在 http{ } 内的子模块中的所有指定就是 HTTP 全局块,会影响 http{ } 及其子模块的内容:

http {
    
    
	# 文件扩展名与文件类型映射表
	include mime.types;
	
	# 默认文件类型
	default_type  application/octet-stream;
	
	# 是否开启服务日志
	access_log off;
	
	# 自定义服务日志格式
	log_format myLogFormat '$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 myLogFormat;
	
	# 是否开启高效文件传输模式
	sendfile on;
	
	# 每个进程每次最大传输值
	sendfile_max_chunk 100k;
	
	# 长连接超时时间
	keeplive_timeout 100;
	
	# 响应客户端的超时时间
	send_timeout 75;
	
	# 客户端请求头的区缓冲区大小
	client_header_buffer_size 32k;
	
	# 客户端请求头的最大缓冲区数量和大小
	large_client_header_buffers 8 32k;
	
	# 允许客户端请求的最大字节数
	client_max_body_size  10m;
	
	# 客户端请求体的缓冲区大小
	client_body_buffer_size  128k;
}

指令详解:

  • 文件扩展名与文件类型映射表在 nginx/conf 下;
  • 默认文件类型的默认值为 text/plain;
  • 是否开启服务日志的默认值为 on,开启了之后需要配置 access_log 路径;
  • sendfile 指令指定 nginx 是否调用 sendfile 函数来输出文件,减少用户空间到内核空间的上下文切换;对于普通应用设为 on,如果用来进行下载等应用磁盘 IO 重负载应用,可设置为 off,以平衡磁盘与网络 I/O 处理速度,降低系统的负载;
  • sendfile_max_chunk 指令的默认为 0,表示不设上限;
  • keeplive_timeout 指令的单位是秒,这个参数很敏感,涉及浏览器的种类、后端服务器的超时设置、操作系统的设置;长连接在请求大量小文件的时候,可以减少重建连接的开销;但如果上传大文件时在设置的超时时间内没上传完成会导致失败,如果设置时间过长,用户又多,长时间保持连接会占用大量资源;
  • send_timeout 指令仅限于两个连接活动之间的时间,如果超过这个时间,客户端没有任何活动,Nginx将会关闭连接;
  • 使用 client_header_buffer_size 指令时,为避免请求 header 过大出现 400 错误,可以适当设置大一点;
  • 使用 large_client_header_buffers 指令时,为避免请求 header 过大出现 400 错误,可以适当设置大一点。

除了这些常用的 http 配置外,还用一些特定的 http 配置,如 反向代理配置:

http {
    
    
    ...
    # 配置 https_proxy 反向代理
    proxy_connect_timeout  75;
    proxy_read_timeout  75;
    proxy_send_timeout 100;
    proxy_buffer_size  4k;
    proxy_buffers  4  32k;
    proxy_busy_buffers_size  64k;
    proxy_max_temp_file_size  64k;
    proxy_temp_file_write_size 64k;
    proxy_temp_path  proxy_temp;
    ...
}

http_proxy 模块指令详解:

  • proxy_connect_timeout :表示 Nginx 跟代理服务器连接超时时间;
  • proxy_read_timeout :表示 Nginx 与代理服务器两个成功的响应操作之间超时时间;
  • proxy_send_timeout :表示 Nginx 传输文件至代理服务器的超时时间;
  • proxy_buffer_size :用于设置从代理服务器读取并保存用户头信息的缓冲区大小;
  • proxy_buffers :设置代理缓冲区大小,Nginx 针对单个连接,缓存来自代理服务器的响应,网页平均在32k以下的话,可以设置为 4 32K ;
  • proxy_busy_buffers_size :设置高负荷下的缓冲大小,一般为 proxy_buffers 的两倍;
  • proxy_max_temp_file_size :当 proxy_buffers 放不下后端服务器的响应内容时,会将一部分保存到硬盘的临时文件中,这个值用来设置最大临时文件大小,默认1024M,它与 proxy_cache 没有关系;大于这个值,将从 upstream 服务器传回,设置为 0 禁用;
  • proxy_temp_file_write_size :当缓存被代理的服务器响应到临时文件时,这个选项限制每次写临时文件的大小;
  • proxy_temp_path :用于指定临时文件所在的目录;

http_gzip 模块配置:

http {
    
    
    ...
    # 配置 http_gzip 模块
    gzip on;
    gzip_min_length 1K;
    gzip_buffers  4  16k;
    gzip_http_version 1.0;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json;
    gzip_proxied any;
    gzip_vray on;
    ...
}
  • gzip :如果设置为 on 则表示开启 gzip 压缩输出,可减少网络传输;
  • gzip_min_length :设置允许压缩的页面最小字节数(到达这个大小才进行压缩),页面字节数从 header 头的 content-length 中进行获取。默认值是 20。建议设置成大于 1k 的字节数,小于 1k 可能会越压越大;
  • gzip_buffers :设置系统获取多少个单位的缓存用于存储 gzip 的压缩结果数据流,4 16k 表示按照原始数据大小以 16k 为单位的 4 倍进行内存申请;
  • gzip_http_version :设置 http 协议的版本,早期的浏览器不支持 Gzip 压缩,用户就会看到乱码,所以为了支持前期版本加上了这个选项;如果你用了 Nginx 的反向代理并启用 Gzip 压缩的话就需要加上,而由于末端通信是 http/1.0,故请设置为 1.0;
  • gzip_comp_level :zip 压缩比,为 1 时,压缩比最小处理速度最快;为 9 时,压缩比最大但处理速度最慢;
  • gzip_types :匹配 mime 类型进行压缩,无论是否指定,text/html 类型总是会被压缩的;
  • gzip_proxied :置开启或者关闭后端服务器返回的结果是否压缩,Nginx 作为反向代理的时候启用,匹配的前提是后端服务器必须要返回包含 Via 的 header头;
  • gzip_vray : 该配置和 http 头有关系,会在响应头加个 Vary: Accept-Encoding ,可以让前端的缓存服务器缓存经过 gzip 压缩的页面,例如:用 Squid 缓存经过 Nginx 压缩的数据;

负载均衡后台服务器列表:

upstream backend {
    
    
	server 192.168.56.10:8080 max_fails=2 fail_timeout=30s backup; # 热备
	server 192.168.56.11:8080 max_fails=2 fail_timeout=30s;
}

Server 块

所有位于 server{} 模块中的指令都属于 Server 块指令:

server {
    
    
    # 监听端口
    listen 8080;
    
    # 监听服务器地址
    server_name 192.168.56.10;
    
    # 每个连接请求上限次数
    keepalive_requests 120;
    
    # 字符集
    charset utf-8;
    
    # 服务日志所在目录以及日志格式
    access_log logs/host80.log myLogFormat;
    
    # 错误页
    error_page  404  /404.html;
	error_page  500 502 503 504  /50x.html;
}

指令详解:

  • 监听的端口,默认80,小于 1024 的要以 root 启动;
  • 监听的服务器地址可以是 IP 或者域名,并且可以使用正则表达式进行匹配;
  • 日志格式的定义和 http 模块的定义方式相同;
  • 错误页的地址为:server_name + error_page;

除了以上常用的 Server 块指令外还有其他特殊的指令,比如 ssl 模块,在请求方式中,如果使用 https 进行请求的话是需要证书,这时就要对 https 请求设置 ssl:

server {
    
    
	# 开启 ssl
	ssl on;
	
	# ssl 证书路径
	ssl_certificate /opt/ssl/nginx.crt;
	
	# ssl 证书秘钥
	ssl_certificate_key /opt/ssl/nginx.key;
	
	# ssl 会话超时时间
	ssl_session_timeout 1d;
	
	# ssl 缓存
	ssl_session_cache shared:SSL:50m;
	
	# ssl 会话票据
	ssl_session_tickets off;
	
	# ssl 协议版本
	ssl_protocols TLSv1.2;
	
	# ssl 密码套件
	ssl_ciphers  'HIGH:!aNULL:!MD5';
	
	# 开启 ssl 服务密码套件
	ssl_prefer_server_ciphers on;
}

Location 块

location  ~*  ^.+$ {
    
    
	# 服务器的默认网站根目录位置
    root /var/www/html;
    
    # 默认访问的文件名
    index  index.html index.htm index.jsp;

	# 拒绝的 IP
	deny 192.168.56.21;
	deny all;

	# 允许的 IP 
	allow 192.168.56.10;
	allow all;
}

指令详解:

  • 紧跟在 location 后面的是 location 模块监听的 url 地址,也就是 location 块的匹配规则,只有匹配正确的地址才会进入该 location 块,可以使用正则表达式进行匹配(~ 表示区分大小写,~* 表示不区分大小写);
  • root :定义服务器的默认网站根目录位置,如果 LocationURL 匹配的是子目录或文件,root 指令没什么作用,一般放在 server 指令里面或 LocationURL 为 / 的 location 块下;
  • index :定义该 location 路径下默认访问的文件名,一般跟 root 的路径放在一起;

设置响应头(可用于访问控制和处理跨域问题):

location {
    
    
    # 设置允许跨域类型
    add_header Access-Control-Allow-Origin * always;
    
    # 是否允许信任证书
    add_header Access-Control-Allow-Credentials 'true' always;
    
    # 允许的请求头类型
    add_header Access-Control-Allow-Headers * always;
    
    # 设置允许的请求方式
    add_header Access-Control-Allow-Methods 'PUT, GET, POST, DELETE, OPTIONS' always;
    
    # 处理 OPTIONS 请求
    if ($request_method = 'OPTIONS') {
    
    
        return 204;
    }
}

指令详解:

  • 为了避免出现失效问题,一般在都在最后面添加 always ;
  • 允许的请求头类型包括:Origin、X-Requested-With、content-Type、Accept、Authorization、uuid 等;

设置反向代理服务器:

location {
    
    
    # 反向代理服务器地址
    proxy_pass  http://192.168.56.33;
        
    # 是否重定向代理服务器地址
    proxy_redirect off;
}

设置向代理服务器发送请求时的请求头数据:

location {
    
    
    # cookie
    proxy_pass_header  Set-Cookie;
    # 主机名
    proxy_set_header Host $host;
    # 真实 IP
    proxy_set_header X-Real-Ip $remote_addr;
    # 表示 HTTP 请求端真实 IP
    proxy_set_header X-Forwarded-For $remote_addr;
}

更多关于 Nginx 配置文档可以参考 Nginx 官方文档

3. nginx.conf 文件详解


#定义Nginx运行的用户和用户组
#user  nobody;

#开启的线程数(默认为1),一般跟逻辑CPU核数一致
worker_processes  1;

 #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug | info | notice | warn | error | crit | alert | emerg
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

 #指定nginx进程运行文件存放地址
#pid        logs/nginx.pid;


events {
    
    
    accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on

    multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off

    use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport

    #单个进程最大连接数(最大连接数=连接数*进程数)
    #根据硬件调整,和前面工作进程配合起来用,尽量大,但是别把cpu跑到100%就行。每个进程允许的最多连接数,理论上每台nginx服务器的最大连接数为。
    worker_connections  1024;

    #keepalive超时时间。
    keepalive_timeout 60;
}


http {
    
    
    #文件扩展名与文件类型映射表
    include       mime.types;

    #默认文件类型
    default_type  application/octet-stream;

    #access_log off; #取消服务日志
  
   #下面代码为日志格式的设定,main为日志格式的名称,可自行设置,后面引用
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #引用日志main
    #access_log  logs/access.log  main;

    #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
    #sendfile指令指定 nginx 是否调用sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为on。如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络IO处理速度,降低系统uptime。
    sendfile        on;

    # 当使用sendfile 函数,tcp_nopush 才起作用,是tcp协议栈中的知识点
    # 当tcp_nopush = on 时,会调用tcp_cork 方法,是默认的,就是收到的数据报不会立即发送出去,而是等到数据报最大时,一次性传输出去,有利于解决网络堵塞。 
    #tcp_nopush     on;

    # 客户端连接超时时间
    # = 0 : 表示禁用长连接。
    # = x :表示长连接timeout
    #keepalive_timeout  0;
    keepalive_timeout  65;

    #HttpGZip模块配置
    #开启gzip压缩
    #gzip  on;

    #设置允许压缩的页面最小字节数
    #gzip_min_length 1k;

    #申请4个单位为16K的内存作为压缩结果流缓存
    #gzip_buffers 4 16k;

    #设置识别http协议的版本,默认为1.1
    #gzip_http_version 1.1;

    #指定gzip压缩比,1-9数字越小,压缩比越小,速度越快
    #gzip_comp_level 2;

    #指定压缩的类型
    #gzip_types text/plain application/x-javascript text/css application/xml;

    #让前端的缓存服务器进过gzip压缩的页面
    #gzip_vary on; 




    #虚拟主机的配置
    server {
    
    
        #监听端口
        listen       80;

        #设置主机域名
        server_name  localhost;

        #设置访问的语言编码
        #charset koi8-r;

        #设置虚拟主机访问日志的存放路径及日志的格式为main
        #access_log  logs/host.access.log  main;

        #设置虚拟主机的基本信息
        location / {
    
    
           #设置虚拟主机的网站根目录
            root   html;

           #设置虚拟主机默认访问的网页
            index  index.html index.htm;
        }

        #对 / 启用反向代理
        location / {
    
    
            proxy_pass  http://127.0.0.1:88;

            #以下是一些反向代理的配置可删除
            proxy_redirect off;

            #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

            #client_max_body_size       10m;   #允许客户端请求的最大单文件字节数
            #client_body_buffer_size    128k;  #缓冲区代理缓冲用户端请求的最大字节数
            #proxy_connect_timeout      300;   #nginx跟后端服务器连接超时时间(代理连接超时)
            #proxy_send_timeout         300;   #后端服务器数据回传时间(代理发送超时)
            #proxy_read_timeout         300;   #连接成功后,后端服务器响应时间(代理接收超时)
            #proxy_buffer_size          4k;    #设置代理服务器(nginx)保存用户头信息的缓冲区大小
            #proxy_buffers              4 32k; #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
            #proxy_busy_buffers_size    64k;   #高负荷下缓冲大小(proxy_buffers*2)
            #proxy_temp_file_write_size 64k;   #设定缓存文件夹大小,大于这个值,将从upstream服务器传
         }

        #设定查看Nginx状态的地址
        location /NginxStatus {
    
    
            stub_status on;
            access_log on;
            auth_basic "NginxStatus";
            auth_basic_user_file confpasswd; #htpasswd文件的内容可以用apache提供的htpasswd工具来产生。
        }

        #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;
    #    }
    #}

}

猜你喜欢

转载自blog.csdn.net/ZYS10000/article/details/127348675