前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Nginx 配置文件详解

Nginx 配置文件详解

作者头像
一个会写诗的程序员
发布2019-08-23 15:46:43
3.3K0
发布2019-08-23 15:46:43
举报

简介

Nginx是lgor Sysoev为俄罗斯访问量第二的rambler.ru站点设计开发的。从2004年发布至今,凭借开源的力量,已经接近成熟与完善。

Nginx功能丰富,可作为HTTP服务器,也可作为反向代理服务器,邮件服务器。支持FastCGI、SSL、Virtual Host、URL Rewrite、Gzip等功能。并且支持很多第三方的模块扩展。

Nginx的稳定性、功能集、示例配置文件和低系统资源的消耗让他后来居上,在全球活跃的网站中有12.18%的使用比率,大约为2220万个网站。

The way nginx and its modules work is determined in the configuration file. By default, the configuration file is named nginx.conf and placed in the directory /usr/local/nginx/conf, /etc/nginx, or /usr/local/etc/nginx.

Starting, Stopping, and Reloading Configuration To start nginx, run the executable file. Once nginx is started, it can be controlled by invoking the executable with the -s parameter. Use the following syntax:

nginx -s signal

Where signal may be one of the following:

stop — fast shutdown
quit — graceful shutdown
reload — reloading the configuration file
reopen — reopening the log files

For example, to stop nginx processes with waiting for the worker processes to finish serving current requests, the following command can be executed:

nginx -s quit

This command should be executed under the same user that started nginx. Changes made in the configuration file will not be applied until the command to reload configuration is sent to nginx or it is restarted. To reload configuration, execute:

nginx -s reload

Once the master process receives the signal to reload configuration, it checks the syntax validity of the new configuration file and tries to apply the configuration provided in it. If this is a success, the master process starts new worker processes and sends messages to old worker processes, requesting them to shut down. Otherwise, the master process rolls back the changes and continues to work with the old configuration. Old worker processes, receiving a command to shut down, stop accepting new connections and continue to service current requests until all such requests are serviced. After that, the old worker processes exit.

A signal may also be sent to nginx processes with the help of Unix tools such as the kill utility. In this case a signal is sent directly to a process with a given process ID. The process ID of the nginx master process is written, by default, to the nginx.pid in the directory /usr/local/nginx/logs or /var/run. For example, if the master process ID is 1628, to send the QUIT signal resulting in nginx’s graceful shutdown, execute:

kill -s QUIT 1628

For getting the list of all running nginx processes, the ps utility may be used, for example, in the following way:

ps -ax | grep nginx

Nginx 配置文件结构

配置文件主要由四部分组成:

main(全局设置)、server(主机设置)、upstream(负载均衡服务器设置)和 location(URL匹配特定位置的设置)。

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

这四者之间的关系式:server继承main,location继承server,upstream既不会继承其他设置也不会被继承。

在这四个部分当中,每个部分都包含若干指令,这些指令主要包含Nginx的主模块指令、事件模块指令、HTTP核心模块指令,同时每个部分还可以使用其他HTTP模块指令,例如Http SSL模块、HttpGzip Static模块和Http Addition模块等。

一个配置文件的例子。

########### 每个指令必须有分号结束。#################
#user administrator administrators;  #配置用户或者组,默认为nobody nobody。
#worker_processes 2;  #允许生成的进程数,默认为1
#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;    #最大连接数,默认为512
}
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;  #热备
    }
    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           
        } 
    }
}

上面是nginx的基本配置,需要注意的有以下几点:

1、几个常见配置项:

$remote_addr 与 $http_x_forwarded_for 用以记录客户端的ip地址;
$remote_user :用来记录客户端用户名称;
$time_local : 用来记录访问时间与时区;
$request : 用来记录请求的url与http协议;
$status : 用来记录请求状态;成功是200;
$body_bytes_s ent :记录发送给客户端文件主体内容大小;
$http_referer :用来记录从那个页面链接访问过来的;
$http_user_agent :记录客户端浏览器的相关信息;

2、惊群现象:一个网路连接到来,多个睡眠的进程被同事叫醒,但只有一个进程能获得链接,这样会影响系统性能。

3、每个指令必须有分号结束。

To apply the new configuration, start nginx if it is not yet started or send the reload signal to the nginx’s master process, by executing:

nginx -s reload

In case something does not work as expected, you may try to find out the reason in access.log and error.log files in the directory /usr/local/nginx/logs or /var/log/nginx.

配置文件详解

#工作进程数,建议设置为CPU的总核数
worker_processes  16;
 
#全局错误日志定义类型,日志等级从低到高依次为:
#debug | info | notice | warn | error | crit
error_log  logs/error.log  info;
 
#记录主进程ID的文件
pid        /nginx-1.13.7/nginx.pid;
 
#一个进程能打开的文件描述符最大值,理论上该值因该是最多能打开的文件数除以进程数。
#但是由于nginx负载并不是完全均衡的,所以这个值最好等于最多能打开的文件数。
#LINUX系统可以执行 sysctl -a | grep fs.file 可以看到linux文件描述符。
worker_rlimit_nofile 65535;
 
#连接数上限,单个进程允许的最大连接数
events {  
    worker_connections  65535;
}
 
#设定http服务器,利用它的反向代理功能提供负载均衡支持
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 记录了哪些用户,哪些页面以及用户浏览器、ip和其他的访问信息
    access_log  logs/access.log  main;
     
    #服务器名字的hash表大小
    server_names_hash_bucket_size 128;
     
    #客户端请求头缓冲大小。
    #nginx默认会用client_header_buffer_size这个buffer来读取header值,
    #如果header过大,它会使用large_client_header_buffers来读取。
    #如果设置过小HTTP头/Cookie过大 会报400 错误 nginx 400 bad request
    #如果超过buffer,就会报HTTP 414错误(URI Too Long)
    #nginx接受最长的HTTP头部大小必须比其中一个buffer大
    #否则就会报400的HTTP错误(Bad Request)
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
 
    #客户端请求体的大小
    client_body_buffer_size    8m;
 
    #隐藏ngnix版本号
    server_tokens off;
 
    #忽略不合法的请求头
    ignore_invalid_headers   on;
 
    #指定启用除第一条error_page指令以外其他的error_page。
    recursive_error_pages    on;
 
    #让 nginx 在处理自己内部重定向时不默认使用  server_name 设置中的第一个域名
    server_name_in_redirect off;
 
    #开启文件传输,一般应用都应设置为on;若是有下载的应用,则可以设置成off来平衡网络I/O和磁盘的I/O来降低系统负载
    sendfile  on;
 
    #告诉nginx在一个数据包里发送所有头文件,而不一个接一个的发送。
    tcp_nopush  on;
 
    #告诉nginx不要缓存数据,而是一段一段的发送--当需要及时发送数据时,就应该给应用设置这个属性,
    #这样发送一小块数据信息时就不能立即得到返回值。
    tcp_nodelay    on;
 
    #长连接超时时间,单位是秒
    keepalive_timeout  65;
 
    #gzip模块设置,使用 gzip 压缩可以降低网站带宽消耗,同时提升访问速度。
    gzip  on;                     #开启gzip
     
    gzip_min_length  1k;          #最小压缩大小
     
    gzip_buffers     4 16k;       #压缩缓冲区
 
    gzip_http_version 1.0;        #压缩版本
 
    gzip_comp_level 2;            #压缩等级
 
    gzip_types   text/plain text/css text/xml text/javascript application/json application/x-javascript application/xml application/xml+rss;          #压缩类型
 
    #upstream作负载均衡,在此配置需要轮询的服务器地址和端口号
    #max_fails为允许请求失败的次数,默认为1.
    #weight为轮询权重,根据不同的权重分配可以用来平衡服务器的访问率。
    #指定要域名对应的WEB项目访问地址
    upstream nginx.www.test.cn {
        server localhost:3000 max_fails=3 weight=1;
    }
 
    #主机配置
    server {
        #监听端口
        listen       90;
 
        #自己指定要跳转的域名
        server_name   192.168.1.19;
         
        #反向代理配置,
        #将所有请求为http://nginx.www.test.cn的请求全部转发到upstream中定义的目标服务器中。
        location / {
            #定义首页索引文件的名称
            #index index.php index.html index.htm;
 
            #此处配置的域名必须与upstream的域名一致,才能转发。
            proxy_pass     http://nginx.www.test.cn;
             
            #以下是一些反向代理的配置可删除
            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服务器传
        }
         
        #单独的access_log文件
        access_log  logs/192.168.1.19.access.log  main;
 
        #设定查看Nginx状态的地址
        location /NginxStatus{
             stub_status on;
             access_log on;
             auth_basic "NginxStatus";
             auth_basic_user_file htpasswd;
        }
                 
        #禁止访问 .htxxx 文件
        location ~ /\.ht {
            deny all;
        }
 
        #字符集
        charset utf-8;
         
        #错误页面
        error_page   500 502 503 504 /50x.html; 
            location = /50x.html {
            root   /root;
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.08.23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • Nginx 配置文件结构
  • 配置文件详解
相关产品与服务
负载均衡
负载均衡(Cloud Load Balancer,CLB)提供安全快捷的流量分发服务,访问流量经由 CLB 可以自动分配到云中的多台后端服务器上,扩展系统的服务能力并消除单点故障。负载均衡支持亿级连接和千万级并发,可轻松应对大流量访问,满足业务需求。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档