Nginx 的完整配置文件结构、配置语法以及模块详解

Nginx 配置文件结构

Nginx 的配置文件通常位于 /etc/nginx/nginx.conf 或安装目录下的 conf/nginx.conf 文件中。配置文件由多个块组成,每个块由一对大括号 {} 包裹,主要包含以下部分:

1. 主配置块

这是配置文件的最外层,包含全局指令,如:

复制代码
user nginx;  # 指定运行 Nginx 的用户
worker_processes  auto;  # 指定工作进程数
error_log /var/log/nginx/error.log;  # 错误日志位置
pid /var/run/nginx.pid;  # PID 文件位置
2. events 块

用于配置与事件相关的指令,主要影响 Nginx 的网络连接处理:

复制代码
events {
    worker_connections 1024;  # 每个工作进程的最大连接数
    use epoll;  # 指定使用的事件驱动模型
}
3. http 块

包含所有与 HTTP 服务器相关的配置,如:

复制代码
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 优化
    keepalive_timeout 65;  # 保持连接的超时时间
    include /etc/nginx/conf.d/*.conf;  # 包含其他配置文件
}
4. server 块

定义一个虚拟主机的配置,可以有多个 server 块,每个块监听不同的端口或主机名:

复制代码
server {
    listen 80;  # 监听的端口
    server_name example.com;  # 服务器名称
    location / {
        root /usr/share/nginx/html;  # 站点根目录
        index index.html index.htm;  # 默认索引文件
    }
}
5. location 块

用于匹配请求的 URI,并定义对该请求的处理方式:

复制代码
location /images/ {
    autoindex on;  # 自动索引目录
}

Nginx 配置语法

Nginx 配置文件的语法由指令和参数组成,每条指令以分号 ; 结束。指令可以包含在块中,块由大括号 {} 包裹。指令的语法如下:

复制代码
指令 参数1 参数2 ...;

Nginx 模块详解

Nginx 提供了多种模块来扩展其功能,以下是一些常见的模块及其用途:

1. ngx_http_core_module

核心模块,提供了基本的 HTTP 功能,如请求处理、响应生成等。

2. ngx_http_access_module

用于基于客户端 IP 地址的访问控制:

复制代码
location / {
    allow 192.168.1.0/24;  # 允许特定 IP 段访问
    deny all;  # 禁止其他 IP 访问
}
3. ngx_http_proxy_module

用于反向代理,将请求转发到后端服务器:

复制代码
location / {
    proxy_pass http://backend;  # 后端服务器地址
    proxy_set_header Host $host;  # 设置请求头
}
4. ngx_http_rewrite_module

用于基于正则表达式的 URL 重写:

复制代码
location / {
    rewrite ^/old/(.*)$ /new/$1 permanent;  # 重写 URL
}
5. ngx_http_upstream_module

用于定义后端服务器组,便于负载均衡:

复制代码
upstream backend {
    server backend1.example.com;
    server backend2.example.com;
}
6. ngx_http_log_module

用于日志记录,可以自定义日志格式:

复制代码
log_format custom '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent"';
access_log /var/log/nginx/access.log custom;
7. ngx_http_ssl_module

用于支持 HTTPS,提供 SSL/TLS 加密:

复制代码
server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
}
8. ngx_http_gzip_module

用于压缩响应内容,减少传输大小:

复制代码
gzip on;
gzip_types text/plain text/css application/json;

这些模块和配置指令可以组合使用,以满足各种复杂的服务器配置需求。