nginx日志格式配置

nginx日志对于统计排错来说非常有利的,nginx 日志相关指令主要有两条,一条是log_format,用来设置日志格式,另外一条是access_log,用来指定日志文件的存放路径、格式和缓存大小,通俗的理解就是先用log_format来定义自己想用的日志格式,然后在用access_log定义虚拟主机时或全局日志时在把定义的log_format 跟在后面。

log_format 格式

log_format name( 格式名字) 格式样式(即想要得到什么样的日志内容)

默认的示例:


log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';

注释:

$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 :记录客户端浏览器的相关信息;

还有更多的参数,可以根据自己的需求定义

用access_log指令日志文件存放路径

用了log_format 指令设置了日志格式之后,需要用access_log指令指定日志文件的存放路径;

access_log path(存放路径) format (自定义日志名称)

示例:

access_log logs/access.log main;

我们用log_format 定义了一个mylogformat的日志 我们可以写成这样

access_log logs/access.log mylogformat ;

如果不想启用日志 :

access_log off ;

注意:

access.log文件是可以按日期进行分割的,方便查看及处理。

为最佳性能调优 Nginx

通常来说,一个优化良好的 Nginx Linux 服务器可以达到 500,000 – 600,000 次/秒 的请求处理性能,然而我的 Nginx 服务器可以稳定地达到 904,000 次/秒 的处理性能,并且我以此高负载测试超过 12 小时,服务器工作稳定。

这里需要特别说明的是,本文中所有列出来的配置都是在我的测试环境验证的,而你需要根据你服务器的情况进行配置:

从 EPEL 源安装 Nginx:

yum -y install nginx

备份配置文件,然后根据你的需要进行配置:

cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.orig
vim /etc/nginx/nginx.conf
# This number should be, at maximum, the number of CPU cores on your system.
# (since nginx doesn't benefit from more than one worker per CPU.)
# 这里的数值不能超过 CPU 的总核数,因为在单个核上部署超过 1 个 Nginx 服务进程并不起到提高性能的作用。
worker_processes 24;
 
# Number of file descriptors used for Nginx. This is set in the OS with 'ulimit -n 200000'
# or using /etc/security/limits.conf
# Nginx 最大可用文件描述符数量,同时需要配置操作系统的 "ulimit -n 200000",或者在 /etc/security/limits.conf 中配置。 
worker_rlimit_nofile 200000;
 
# only log critical errors
# 只记录 critical 级别的错误日志
error_log /var/log/nginx/error.log crit
 
# Determines how many clients will be served by each worker process.
# (Max clients = worker_connections * worker_processes)
# "Max clients" is also limited by the number of socket connections available on the system (~64k)
# 配置单个 Nginx 单个进程可服务的客户端数量,(最大值客户端数 = 单进程连接数 * 进程数 )
# 最大客户端数同时也受操作系统 socket 连接数的影响(最大 64K )
worker_connections 4000;
 
# essential for linux, optmized to serve many clients with each thread
# Linux 关键配置,允许单个线程处理多个客户端请求。
use epoll;
 
# Accept as many connections as possible, after nginx gets notification about a new connection.
# May flood worker_connections, if that option is set too low.
# 允许尽可能地处理更多的连接数,如果 worker_connections 配置太低,会产生大量的无效连接请求。
multi_accept on;
 
# Caches information about open FDs, freqently accessed files.
# Changing this setting, in my environment, brought performance up from 560k req/sec, to 904k req/sec.
# I recommend using some varient of these options, though not the specific values listed below.
# 缓存高频操作文件的FDs(文件描述符/文件句柄)
# 在我的设备环境中,通过修改以下配置,性能从 560k 请求/秒 提升到 904k 请求/秒。
# 我建议你对以下配置尝试不同的组合,而不是直接使用这几个数据。
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
 
# Buffer log writes to speed up IO, or disable them altogether
# 将日志写入高速 IO 存储设备,或者直接关闭日志。
# access_log /var/log/nginx/access.log main buffer=16k;
access_log off;
 
# Sendfile copies data between one FD and other from within the kernel.
# More efficient than read() + write(), since the requires transferring data to and from the user space.
# 开启 sendfile 选项,使用内核的 FD 文件传输功能,这个比在用户态用 read() + write() 的方式更加高效。
sendfile on;
 
# Tcp_nopush causes nginx to attempt to send its HTTP response head in one packet,
# instead of using partial frames. This is useful for prepending headers before calling sendfile,
# or for throughput optimization.
# 打开 tcp_nopush 选项,Nginux 允许将 HTTP 应答首部与数据内容在同一个报文中发出。
# 这个选项使服务器在 sendfile 时可以提前准备 HTTP 首部,能够达到优化吞吐的效果。
tcp_nopush on;
 
# don't buffer data-sends (disable Nagle algorithm). Good for sending frequent small bursts of data in real time.
# 不要缓存 data-sends (关闭 Nagle 算法),这个能够提高高频发送小数据报文的实时性。
tcp_nodelay on;
 
# Timeout for keep-alive connections. Server will close connections after this time.
# 配置连接 keep-alive 超时时间,服务器将在超时之后关闭相应的连接。
keepalive_timeout 30;
 
# Number of requests a client can make over the keep-alive connection. This is set high for testing.
# 单个客户端在 keep-alive 连接上可以发送的请求数量,在测试环境中,需要配置个比较大的值。
keepalive_requests 100000;
 
# allow the server to close the connection after a client stops responding. Frees up socket-associated memory.
# 允许服务器在客户端停止发送应答之后关闭连接,以便释放连接相应的 socket 内存开销。
reset_timedout_connection on;
 
# send the client a "request timed out" if the body is not loaded by this time. Default 60.
# 配置客户端数据请求超时时间,默认是 60 秒。
client_body_timeout 10;
 
# If the client stops reading data, free up the stale client connection after this much time. Default 60.
# 客户端数据读超时配置,客户端停止读取数据,超时时间后断开相应连接,默认是 60 秒。
send_timeout 2;
 
# Compression. Reduces the amount of data that needs to be transferred over the network
# 压缩参数配置,减少在网络上所传输的数据量。
gzip on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-6].";

启动 Nginx 并配置开机自动启动。

service nginx start
chkconfig nginx on

构建强健的HTTPS网站:Nginx SSL 配置优化

开启SPDY

SPDY(音:speedy)是Google开发的基于TCP的应用层协议,用以加速网站通信,减少带宽使用,优化用户的网络使用体验。SPDY并不是一种用于替代HTTP的协议,而是对HTTP协议的增强。详情请看https://developers.google.com/speed/spdy/。另外HTTP/2是基于SPDY/2来开发的。按照官网的说法的好处就是:

  • 压缩报头和去掉不必要的头部来减少当前HTTP使用的带宽
  • 单个TCP连接支持并发的HTTP请求
  • 允许服务器在需要时发起对客户端的连接并推送数据(比如css,js等)。

Nginx1.5.10以前支持SPDY/2,以后的版本支持SPDY/3. 源码编译请加–with-http_spdy_module来启用SPDY模块。另外为了在同一个端口同时处理HTTPS和SPDY连接。 OpenSSL必须支持NPN(Next Protocol Negotiation)TLS扩展, 意思要openssl的版本要求要>=1.0.1


listen 443 ssl spdy; #启用SPDY。
spdy_headers_comp 0; #header压缩等级,默认不压缩。0-9
spdy_chunk_size 8k; #SPDY块大小,默认8k

网站是否启用SPDY可以通过SPDYcheck来检测,另外可以通过chrome://net-internals 里的SPDY标签中SPDY sessions查看是否有该网站建立的会话。

使用安全的TLS协议

如果不配置ssl_protocols,Nginx默认使用SSLv3 TLSv1 TLSv1.1 TLSv1.2。但是SSLv3协议爆出了POODLE漏洞,所以现在SSL3协议是不安全的,整个SSL协议组我们都不应该使用,除非是为了兼容旧有的一些客户端并且应该谨慎安全的配置。从此以后,我们应该使用更安全的TLS协议。Nginx需要openssl版本>=1.0.1来支持TLSv1.2协议。

ssl_protocols TLSv1 TLSv1.1 TLSv1.2

设置SSL会话缓存

设置SSL会话缓存,将可以使客户端在一定时间内复用这个SSL会话而不需要重新进行TLS握手建立SSL会话,并且也可以减少服务器资源的占用。使用ssl_session_cache,据Nginx官方手册介绍每1M缓存可以存储4000个会话。这个设置在流量大的HTTPS网站可以有显著效果,提升服务器处理SSL并发连接的能力。

ssl_session_cache shared:SSL:10m; #使用10m共享内存
ssl_session_timeout 10m; #设置会话过期时间为10分钟

设置OCSP stapling

OCSP(Online Certificate Status Protocol)在线证书状态协议,用来验证网站证书有效性。使用OCSP可以加快HTTPS链接的建立、减少客户端带宽使用,因为OCSP克服了证书注销列表(CRL)的主要缺陷:必须经常在客户端下载以确保列表的更新。浏览器只需要向证书提供的OSCP服务器发送1个请求就可以验证证书状态而不需要下载整个CRL。
如果ssl_certificate中没有包含中级证书,我们就必须设置ssl_trusted_certificate,里面包含PEM格式的CA根证书和中级证书。比如本站的SSL证书是AlphaSSL证书,而AlphaSSL是GlobalSign这个CA签发的中级证书。

ssl_stapling on; 
ssl_stapling_verify on; 
ssl_trusted_certificate conf.d/cert/AlphaSSLroot.crt; #
resolver 8.8.8.8; #添加resolver解析OSCP响应服务器的主机名

开启HSTS

HSTS(HTTP Strict Transport Security)强制安全传输技术是一种网站安全机制,它会让浏览器强制使用HTTPS来请求网站资源,用以防止一些恶意行为。具体请参见RFC6797。而开启HSTS只需要添加一个header就可以

add_header Strict-Transport-Security "max-age=31536000"; 365天内使用HTTPS访问网站

使用安全的加密套件

ssl_ciphers定义了网站使用那些加密套件,nginx的默认设置是HIGH:!aNULL:!MD5;这个值已经是比较安全的。最主要的是ssl_prefer_server_ciphers的设置,开启这个设置可以优先使用服务器定义的加密算法以防止Beast Attacks。

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

使用2048位的DHE Paramaters

如果没有定义ssl_dhparam的话,Nginx默认使用openssl随机生成的1024位
使用openssl生产2048位的

openssl gendh -out dh2048.pem 2048

设置Nginx的ssl_dhparam参数

ssl_dhparam conf.d/cert/dh2048.pem;

配置文件完整示例

如果是使用通配符证书(Wildcard Certificate),可以添加到nginx.conf里的http{}配置段中,所有开启了ssl的网站共享配置。


#Add SPDY Support
listen 443 ssl spdy;
#SSL Certificate
ssl_certificate conf.d/cert/wildcard_chenpei.org.crt;
ssl_certificate_key conf.d/cert/wildcard_chenpei.org.key;
#TLS only
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
#SSL Session Cache
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
#OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate conf.d/cert/AlphaSSLroot.crt;
resolver 8.8.8.8;
#HSTS
add_header Strict-Transport-Security "max-age=31536000";
#Disable Beast Attacks
ssl_prefer_server_ciphers on;
#Stronger DHE Parameters
ssl_dhparam conf.d/cert/dh2048.pem;