NginX配置详解
NginX配置详解
一、配置文件
1.1 配置文件路径
主配置文件默认路径为conf/nginx.conf。
1.2 配置文件结构
1.2.1 全局块
配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。
1.2.2 events块
配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。
1.2.3 http块
可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。
1.2.4 server块
配置虚拟主机的相关参数,一个http中可以有多个server。
1.2.5 location块
配置请求的路由,以及各种页面的处理情况。
1.2.6 使用include文件
在Nginx的配置文件中,include文件可以在任何地方,以便增强文件的可读性。如果没有给定全路径,Nginx将会依据他的主配置文件路径进行搜索。
二、配置项说明
2.1 全局块
2.1.1 设定worker进程的启动数量
worker_processes auto;
#worker进程数,与CPU核数相同,一般使用auto即可。2.1.2 设定worker进程的CPU亲和
worker_cpu_affinity auto;
#worker的CPU亲和。
worker_cpu_affinity 00000001 00000010 00000100 0000100000010000 00100000 01000000 10000000;
#设置CPU亲和力,绑定worker进程的cpu核心,防止多个进程跑在一个核心上,以减少开销。
worker_cpu_affinity 0001 0010 0100 1000;
#若为4核则如此配置2.1.3 设定worker进程的进程优先级
worker_priority -20;
#进程优先级,-20~19。数字越小优先级越高。2.1.4 设定worker进程最大打开文件数
worker_rlimit_nofile 4096;
#可打开最大文件描述符数量。
#此值是worker_connections值*worker_processes值(即CPU核心数)。
#每个worker进程可打开的最大文件数是worker_rlimit_nofile/worker_processes(即CPU核心数)个。
#如果达到打开文件数的上限,客户端访问服务器将会提示“Too many open files”。操作系统层面设置
vim /etc/security/limits.conf
#配置文件路径
#limits.conf配置文件
#修改配置文件
* soft nproc 65535
* hard nproc 65535
#用户可开启进程的最大数目。
* soft nofile 65535
* hard nofile 65535
#用户可打开文件的最大数目。
#soft软限制,hard硬限制。 * - nofile 65535,使用“-”表示同时设定soft和hard。
#使用ulimit命令
ulimit -a
#查看系统用户所有限制值。
ulimit -n
#直接查看当前进程可以打开文件的最大数量,默认是1024。
reboot
#重启系统后生效systemd相关配置
#使用systemd启动,需在service文件的[service]块中添加配置项:LimitNOFILE=65536
[Unit]
Description=nginx service
After=network.target
[Service]
Type=forking
ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
ExecReload=/apps/nginx/sbin/nginx -s reload
ExecStop=/apps/nginx/sbin/nginx -s quit
KillSignal=SIGQUIT
PrivateTmp=true
LimitNOFILE=65536
#配置nofile数量
[Install]
WantedBy=multi-user.target2.1.5 其他配置
daemon off;
#设置为on则将在后台运行。设置为off则在前台运行,用于容器环境和测试。master_process on;
#开启master-worker工作模式,默认为on。若off则不创建会worker进程。2.2 events块
2.2.1 worker进程能够接受的并发连接数
worker_connections 1024;
#单个工作进程可以允许同时建立外部连接的数量。无论这个连接是外部主动建立的,还是内部建立的。
#nginx能接受的同时并发数量为1024个*8核=8192个。2.2.2 使用epoll模型
use epoll;
#epoll是Linux内核为处理大批量文件描述符而作了改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显著提高程序在大量并发连接中只有少量活跃的情况下的系统CPU利用率。2.2.3 惊群设置
accept_mutex on;
#惊群设置,默认为off。当有请求时唤醒所有进程。设置为on后,请求由worker轮流处理,而非唤醒全部进程。2.2.4 多请求同时响应
multi_accept on;
#设置为on后,单个worker进程可以同时接受多个新请求。默认为off。2.3 HTTP块
2.3.1 sendfile相关设置
sendfile on;
#sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,降低系统的uptime.
#在服务器应用程序中使用sendfile()能够显著的减少对CPU的占用。tcp_nopush on;
#选项仅在使用sendfile的时候才开启。
tcp_nodelay on;
#默认为on,立即发送用户报文,没有延迟。
#设置为off时则会启用Nagle算法,会有一定的延迟,约为40-200毫秒。
#Nagle算法是为了提高网络传输效率。2.3.2 keepalive超时时间
keepalive_timeout 60;
#keepalive 超时时间,0表示禁止长连接,默认为75s。客户端到服务器端的连接持续有效时间,当出现对服务器的后继请求时,keepalive-timeout 功能可避免建立或重新建立连接。
keepalive_timeout 60 60;
#可设置2个值,第一个值为超时时间,第二个值为发送给客户端应答报文头部中显示的超时时间设置(header_timeout)。
keepalive_requests 100;
#在一次长连接中所允许请求的资源的最大数量,默认为100。建议适当调大。2.3.3 缓存相关设置
client_header_buffer_size 4k;
#客户端请求头部的缓冲区大小。这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。
#分页大小可以用命令getconf PAGESIZE 取得。open_file_cache max=65535 inactive=60s;
#这个将为打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致,inactive是指经过多长时间文件没被请求后删除缓存。
open_file_cache_valid 80s;
#这个是指多长时间检查一次缓存的有效信息。
open_file_cache_min_uses 1;
#open_file_cache指令中的inactive参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive时间内一次没被使用,它将被移除。2.3.4 设置默认字符编码
charset utf-8;
#设置字符编码类型。2.3.5 隐藏nginx软件信息
server_tokens off;
#设置为off不显示nginx版本号。
#但nginx软件名称仍然会显示。如果需要修改或隐藏软件名称。见下文。2.3.6 上传文件大小配置
client_max_body_size 200m;
#允许最大的客户端请求头。(客户端上传文件大小。)2.3.7 压缩功能
gzip on;
#开启压缩功能,默认关闭。
gzip_comp_level 1;
#压缩比,从低到高为1-9。推荐5,默认为1。
gzip_disable "MSIE [1-6]\.";
#禁用IE6的gzip功能。
gzip_min_length 1k;
#小于此值的文件将不会被压缩。默认为20k。
gzip_http_version 1.0;
#启用压缩功能时,http协议的最小版本。默认为1.1版本。
gzip_buffers 32 4k;
#指定nginx向服务器申请的缓存空间的数量和大小。
#设置用于压缩响应的 number 和 size 的缓冲区。默认情况下,缓冲区大小等于一个内存页。根据平台的不同,它也可以是4K或8K。
gzip_vary on;
#是否在响应报文中加入Vary:Accept-Encoding
gzip_proxied any;
#是否开启对代理资源的压缩。很多时候,nginx 会作为反向代理服务器,实际的静态资源在上有服务器上,只有开启了 gzip_proxied 才会对代理的资源进行压缩。默认off。
gzip_static on;
#服务器开启对静态文件(CSS,JS,HTML,SVG,ICS,JSON)的压缩。但是,要使此部分与之相关,需要在 gzip_types 设置 MIME 类型,仅仅设置 gzip_static为on是不会自动压缩静态文件的。
gzip_types
application/javascript
application/x-javascript
text/javascript
text/css
text/xml
application/xhtml+xml
application/xml
application/atom+xml
application/rdf+xml
application/rss+xml
application/geo+json
application/json
application/ld+json
application/manifest+json
application/x-web-app-manifest+json
image/svg+xml
text/x-cross-domain-policy;
#指明进行压缩的资源类型
#默认为text/html,此项无需显示指定。2.3.8 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#log日志格式
#只能配置在http模块中
access_log logs/access.log main;
#可以配置在http、server、location中
#不同网站可以建立独立的日志文件中,便于查看 Nginx 的默认访问日志记录内容相对比较单一,默认的格式也不方便后期做日志统计分析,生产环境中 通常将nginx日志转换为json日志,然后配合使用ELK做日志收集,统计和分析。
log_format access_json '{"@timestamp":"$time_iso8601",'
'"host":"$server_addr",'
'"clientip":"$remote_addr",'
'"size":$body_bytes_sent,'
'"responsetime":$request_time,' #总的处理时间
'"upstreamtime":"$upstream_response_time",'
'"upstreamhost":"$upstream_addr",' #后端应用服务器处理时间
'"http_host":"$host",'
'"uri":"$uri",'
'"xff":"$http_x_forwarded_for",'
'"referer":"$http_referer",'
'"tcp_xff":"$proxy_protocol_addr",'
'"http_user_agent":"$http_user_agent",'
'"status":"$status"}';
access_log /apps/nginx/logs/access_json.log access_json;2.4 Server块
任何由关键字server开始的部分都被称作“虚拟服务器”部分。它描述的是一组根据server_name指定逻辑分割的资源,这些虚拟服务器相应http请求,因此他们都包含在http部分中。
一个虚拟服务器由listen和server_name指令组合定义,listen指令定义了一个ip地址/端口组合或者是UNIX域套接字路径。
#这里是一个配置了ssl证书的web虚拟主机示例配置文件。
server {
listen 443 ssl;
server_name example.com;
root html;
index index.html index.htm;
ssl_certificate cert/example.com.pem;
ssl_certificate_key cert/example.com.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
#php-fpm相关配置。
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
#这里配置了80端口监听,并将针对80端口的访问,重定向到443端口。
server {
listen 80;
server_name example.com;
rewrite ^(.*)$ https://$host$1 permanent;
location / {
index index.html index.htm index.php;
}
}2.5 Location块
locations指令可以用在虚拟服务器server部分,并且意味着提供来自客户端的URL或者内部重定向访问。除少数情况外,locations也可以备嵌套使用,他们被作为特定的配置尽可能地处理请求。
location / {
root html;
index index.html index.htm index.php;
}| 修饰符 | 处理方式 |
|---|---|
| = | 使用精确匹配并终止搜索。 |
| ~ | 区分大小写的正则表达式。 |
| ~* | 不区分大小写的正则表达式。 |
| ^~ | 匹配开头。如果该location是最佳匹配,那么对于匹配这个location的字符串不再进行正则表达式检测。注意这不是一个正则表达式匹配,它的目的是优先于正则表达式的匹配。 |
| $ | 以字符串结尾 |
2.5.1 alias别名
定义location的其他名字,在文件系统中能够找到。如果一个location指定了一个正则表达式,alias将会引用正则表达式中定义的捕获。alias替代location中匹配的部分,没有匹配的部分将会在文件系统中搜索。当配置改变一点,配置中使用alias则会有脆弱的表现,因此推荐使用root,除非是为了找到文件而需要修改。
2.5.2 expires页面缓存
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico|woff)$ {
expires 30d;
access_log off;
}
#图片文件缓存30天。
location ~ .*\.(js|css)?$ {
expires 7d;
access_log off;
}
#js和css保存7天。2.5.3 安全性
location ~ /\.ht {
deny all;
}
#禁止访问.htaccess文件
#.htaccess文件包含了我们站点中所有的文件目录和路径2.5.4 try_files 检测文件是否存在
try_files会按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾以斜线表示为文件夹),如果所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内部500错误。
try_files $uri $uri/index.html /index.html2.5.5 限速
limit_rate 100;
#限制响应客户端传输速率(除GET和HEAD以外的所有方法),单位B/s,即bytes/second,默认值0,表示无限制,此指令由ngx_http_core_module提供。
limit_rate 100k;
limit_rate 2m;
#可以直接使用k、m来进行限速。2.5.6 自动目录相关
支持在server和location块中添加
autoindex on;
#开启自动目录
autoindex_exact_size off;
#设置为on显示精确的文件大小,精确值为字节,可读性不好。
#设置为off则以KB、MB、GB等来表示文件大小,可读性好。
autoindex_localtime on;
#显示本机时间,而非GMT时间。默认为off
autoindex_format html;
#html/xml/json/jsonp
#显示索引的页面文件风格,默认html2.5.7 方法限制
limit_except GET {
allow 192.168.0.0/24;
allow 192.168.0.1;
deny all;
}
#除了GET方法以外的方法,192.168.0.0网段的主机可以使用,其它主机不能使用。
#限制客户端使用指定的请求之外的其他方法。
#GET,HEAD,POST,PUT,DELETE,MKCOL,COPY,MOVE,OPTIONS,PROPFIND,PROPPATCH,LOCK,UNLOCK,PATCH2.6 其它设置
2.6.1 修改nginx的名称和隐藏版本号
修改nginx名称信息
src/core/nginx.h
#修改此文件
#define NGINX_VERSION "1.22.0"
#define NGINX_VER "nginx/" NGINX_VERSION
#修改对应名称和版本号若使用server_tokens off选项,则需修改如下位置:
src/http/ngx_http_header_filter_module.c
#修改此文件
static u_char ngx_http_server_string[] = "Server: nginx" CRLF;
#修改为所需名称配置完毕后编译。
2.6.2 nginx状态页
模块名称ngx_http_stub_status_module
location = /basic_status {
stub_status;
allow 192.168.0.0/24;
deny all;
}返回值
| 值 | 用途 |
|---|---|
| Active connections | 当前处于活动中的客户端连接数,包括等待空闲连接数。 |
| accepts | 统计总值,nginx自启动后已经接受的客户端请求的总数。 |
| handled | 统计总值,nginx自启动后已经处理完成的客户端请求的总数,通常等于accepts,除非有因为worker_connections限制等原因被拒绝的连接。 |
| requests | 统计总值,nginx自启动后客户端发来的请求总数。 |
| reading | 当前状态,正在读取客户端请求报文首部的连接的连接数。 |
| writing | 当前状态,正在向客户端发送响应报文过程中的连接数。 |
| waiting | 当前状态,正在等待客户端发出请求的空闲连接数,开启keep-alive的情况下,这个值等于active - ( reading + writing ) |
四、配置文件实例
4.1 默认配置文件
#user nobody;
worker_processes auto;
#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;
# }
#}
}4.2 PHP项目配置文件
server {
listen 8087;
#server_name _;
#access_log /data/wwwlogs/example.log combined;
error_log /data/wwwlogs/example.log;
root /data/wwwroot/default/example/;
index index.html index.htm index.php;
location / {
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php/$1 last;
}
}
location ~ [^/]\.php(/|$) {
#fastcgi_pass remote_php_ip:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico|woff)$ {
expires 30d;
access_log off;
}
location ~ .*\.(js|css)?$ {
expires 7d;
access_log off;
}
location ~ /\.ht {
deny all;
}
}