Nginx配置文件主要包含全局块、HTTP块、Server块和Location块四个部分,每个部分中的代码有不同的作用。下面是一个简单的Nginx配置文件,并对每一行代码进行解释:
user nginx; # Nginx进程的运行用户
worker_processes auto; # 工作进程的数量,一般设为CPU的核数
error_log /var/log/nginx/error.log warn; # 错误日志文件路径和日志级别
pid /var/run/nginx.pid; # Nginx进程的PID文件路径
events {
worker_connections 1024; # 最大并发连接数
}
http {
include /etc/nginx/mime.types; # MIME类型定义文件路径
default_type application/octet-stream; # 默认MIME类型
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 /var/log/nginx/access.log main; # 访问日志文件路径和日志格式
sendfile on; # 开启sendfile特性
tcp_nopush on; # 开启tcp_nopush特性
tcp_nodelay on; # 开启tcp_nodelay特性
keepalive_timeout 65; # 连接超时时间
gzip on; # 开启gzip压缩
include /etc/nginx/conf.d/*.conf; # 载入conf.d目录下的所有配置文件
server {
listen 80; # 监听端口
server_name example.com; # 域名
root /var/www/example.com; # 网站根目录
index index.html; # 默认首页文件名
location / {
try_files $uri $uri/ /index.html; # URL重写规则
}
}
}
上述代码中,每行代码的作用如下:
user nginx;:指定Nginx进程的运行用户,一般使用非root用户来运行Nginx进程,提高安全性;
worker_processes auto;:指定工作进程的数量,auto表示根据CPU核数自动设置;
error_log /var/log/nginx/error.log warn;:指定错误日志文件路径和日志级别,warn表示只记录警告及以上级别的错误信息;
pid /var/run/nginx.pid;:指定Nginx进程的PID文件路径;
events {...}:事件块,用于设置Nginx与操作系统交互的事件模型;
worker_connections 1024;:设置每个工作进程的最大并发连接数;
http {...}:HTTP块,用于配置全局的HTTP选项;
include /etc/nginx/mime.types;:载入MIME类型定义文件,用于指定文件的Content-Type;
default_type application/octet-stream;:设置默认的MIME类型;
`log_format main '$remote_addr - $remote_user [$time_local] "$request" ' :定义日志格式,包括远程客户端IP地址、远程用户、访问时间、请求方法和请求的URI;
'$status $body_bytes_sent "$http_referer" ' :添加状态码、发送字节数、HTTP Referer头部;
'"$http_user_agent" "$http_x_forwarded_for" ':添加用户代理和X-Forwarded-For头部,用于记录客户端信息;
'$request_time $upstream_response_time $pipe';:添加请求响应时间和与后端服务器的连接时间。