Nginx配置基础 #

一、配置文件位置 #

Nginx配置文件的位置因安装方式而异:

安装方式 配置文件位置
apt/yum安装 /etc/nginx/nginx.conf
源码编译 /usr/local/nginx/conf/nginx.conf
Homebrew /usr/local/etc/nginx/nginx.conf
Windows conf/nginx.conf

二、配置文件结构 #

Nginx配置文件采用嵌套的块结构,由多个上下文(Context)组成:

text
main(全局配置)
├── events(事件配置)
├── http(HTTP配置)
│   ├── upstream(上游服务器)
│   ├── server(虚拟主机)
│   │   └── location(位置匹配)
│   └── ...
├── mail(邮件配置)
└── stream(TCP/UDP代理)

2.1 基本配置示例 #

nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;
    
    sendfile        on;
    keepalive_timeout  65;
    
    server {
        listen       80;
        server_name  localhost;
        
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
    }
}

三、全局配置(main) #

全局配置位于配置文件最外层,影响Nginx整体运行。

3.1 用户和进程配置 #

nginx
user nginx;
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
pid /var/run/nginx.pid;
指令 说明 默认值
user worker进程运行用户 nobody
worker_processes worker进程数量 1
worker_cpu_affinity CPU亲和性绑定 -
worker_rlimit_nofile 最大打开文件数 自动
pid PID文件位置 logs/nginx.pid

3.2 错误日志配置 #

nginx
error_log /var/log/nginx/error.log warn;
error_log /var/log/nginx/error.log info;
error_log /dev/null;

日志级别:debug > info > notice > warn > error > crit > alert > emerg

3.3 包含其他配置 #

nginx
include /etc/nginx/modules-enabled/*.conf;
include /etc/nginx/conf.d/*.conf;

四、事件配置(events) #

events块配置连接处理相关参数:

nginx
events {
    worker_connections  10240;
    use epoll;
    multi_accept on;
    accept_mutex on;
    accept_mutex_delay 500ms;
}
指令 说明 默认值
worker_connections 每个worker最大连接数 512
use 事件驱动模型 自动选择
multi_accept 一次接受多个连接 off
accept_mutex 连接互斥锁 on
accept_mutex_delay 获取锁等待时间 500ms

最大并发连接数计算:

text
最大并发 = worker_processes × worker_connections

五、HTTP配置(http) #

http块是Nginx Web服务器的核心配置区域。

5.1 基本设置 #

nginx
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    
    charset utf-8;
    server_tokens off;
    
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;
    types_hash_max_size 2048;
}
指令 说明
include 包含MIME类型定义文件
default_type 默认MIME类型
charset 默认字符集
server_tokens 隐藏Nginx版本号
sendfile 使用sendfile系统调用
tcp_nopush 优化数据包发送
tcp_nodelay 禁用Nagle算法
keepalive_timeout 长连接超时时间

5.2 日志格式 #

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

log_format  json  escape=json '{'
    '"time":"$time_iso8601",'
    '"remote_addr":"$remote_addr",'
    '"request":"$request",'
    '"status":"$status",'
    '"body_bytes_sent":"$body_bytes_sent",'
    '"request_time":"$request_time",'
    '"http_referrer":"$http_referer",'
    '"http_user_agent":"$http_user_agent"'
'}';

access_log  /var/log/nginx/access.log  main;
access_log  /var/log/nginx/access.json  json;

5.3 Gzip压缩 #

nginx
gzip  on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_types text/plain text/css application/json application/javascript 
           text/xml application/xml application/xml+rss text/javascript;
gzip_disable "msie6";

六、Server块(虚拟主机) #

server块定义虚拟主机,一个http块可以包含多个server块。

6.1 基本结构 #

nginx
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    root /var/www/example;
    index index.html index.htm;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

6.2 listen指令 #

nginx
listen 80;
listen 8080;
listen 192.168.1.100:80;
listen 80 default_server;
listen 443 ssl;
listen [::]:80 ipv6only=on;
参数 说明
default_server 默认虚拟主机
ssl 启用SSL
http2 启用HTTP/2
ipv6only=on 仅监听IPv6

6.3 server_name指令 #

server_name支持多种匹配方式:

nginx
server_name example.com;
server_name example.com www.example.com;
server_name *.example.com;
server_name example.*;
server_name ~^(?<user>.+)\.example\.com$;
server_name "";
匹配方式 示例 优先级
精确匹配 example.com 1(最高)
前缀通配符 *.example.com 2
后缀通配符 example.* 3
正则表达式 ~^(.+).example.com$ 4

七、Location块 #

location块定义请求的处理方式,是Nginx配置的核心。

7.1 匹配语法 #

nginx
location = / {
}

location / {
}

location /images/ {
}

location ^~ /images/ {
}

location ~ \.(gif|jpg|jpeg)$ {
}

location ~* \.(gif|jpg|jpeg)$ {
}
修饰符 说明 示例
= 精确匹配 location = /
前缀匹配 location /
^~ 前缀匹配(优先) location ^~ /images/
~ 区分大小写正则 location ~ .php$
~* 不区分大小写正则 location ~* .php$

7.2 匹配优先级 #

text
1. = 精确匹配(最高优先级)
2. ^~ 前缀匹配
3. ~ 和 ~* 正则匹配(按配置顺序)
4. 无修饰符前缀匹配(最长匹配)

7.3 匹配示例 #

nginx
server {
    listen 80;
    server_name example.com;
    
    location = / {
        return 200 "精确匹配根路径";
    }
    
    location / {
        return 200 "前缀匹配";
    }
    
    location /images/ {
        return 200 "匹配/images/路径";
    }
    
    location ^~ /static/ {
        return 200 "优先匹配/static/";
    }
    
    location ~ \.php$ {
        return 200 "正则匹配PHP文件";
    }
    
    location ~* \.(gif|jpg|png)$ {
        return 200 "正则匹配图片";
    }
}

八、变量系统 #

Nginx内置了大量变量,可在配置中使用。

8.1 常用内置变量 #

nginx
$remote_addr
$remote_port
$remote_user
$request
$request_method
$request_uri
$scheme
$host
$server_name
$server_port
$uri
$args
$arg_name
$http_name
$cookie_name
$document_root
$status
$body_bytes_sent
$request_time
$time_iso8601

8.2 自定义变量 #

nginx
set $my_var "hello";
set $full_uri $scheme://$host$uri;

location /test {
    set $debug "on";
    return 200 "debug: $debug, uri: $uri";
}

8.3 变量使用示例 #

nginx
location / {
    if ($request_method = POST) {
        return 405;
    }
    
    if ($http_user_agent ~* "bot") {
        return 403;
    }
    
    if ($args ~ "debug=1") {
        return 200 "Debug mode enabled";
    }
}

九、配置最佳实践 #

9.1 配置文件组织 #

text
/etc/nginx/
├── nginx.conf
├── conf.d/
│   ├── default.conf
│   └── ssl.conf
├── sites-available/
│   ├── site1.conf
│   └── site2.conf
├── sites-enabled/
│   ├── site1.conf -> ../sites-available/site1.conf
│   └── site2.conf -> ../sites-available/site2.conf
├── snippets/
│   ├── ssl-params.conf
│   └── proxy-params.conf
└── modules-enabled/
    └── *.conf

9.2 使用include拆分配置 #

nginx
http {
    include /etc/nginx/snippets/proxy-params.conf;
    
    server {
        listen 80;
        include /etc/nginx/snippets/ssl-params.conf;
        
        location / {
            include /etc/nginx/snippets/proxy-params.conf;
            proxy_pass http://backend;
        }
    }
}

9.3 公共配置片段 #

proxy-params.conf:

nginx
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

ssl-params.conf:

nginx
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

十、配置测试与重载 #

10.1 测试配置语法 #

bash
nginx -t
nginx -t -c /etc/nginx/nginx.conf

10.2 重载配置 #

bash
nginx -s reload
systemctl reload nginx

10.3 查看编译参数 #

bash
nginx -V

十一、总结 #

本章我们学习了:

  1. 配置文件结构:main、events、http、server、location层级关系
  2. 全局配置:用户、进程、日志等基础设置
  3. 事件配置:连接处理参数
  4. HTTP配置:MIME类型、日志、压缩等
  5. Server块:虚拟主机配置
  6. Location块:请求匹配规则
  7. 变量系统:内置变量和自定义变量

掌握配置基础后,让我们进入下一章,学习Nginx基本命令!

最后更新:2026-03-27