当前位置: 代码网 > 服务器>服务器>Linux > Nginx 配置示例及核心模块详解

Nginx 配置示例及核心模块详解

2026年02月12日 Linux 我要评论
nginx 配置详解一、配置文件结构# 全局块(主配置)main# 事件块events { ...}# http 块http { # http 全局配置 ... # 虚拟主机块

nginx 配置详解

一、配置文件结构

# 全局块(主配置)
main
# 事件块
events {
    ...
}
# http 块
http {
    # http 全局配置
    ...
    # 虚拟主机块(一个或多个)
    server {
        # 服务器配置
        ...
        # 位置块(一个或多个)
        location {
            ...
        }
    }
    # 可包含其他配置文件
    include /etc/nginx/conf.d/*.conf;
}

二、核心模块详解

1. 全局配置(main context)

user nginx nginx;          # 运行用户和组
worker_processes auto;      # 工作进程数(auto = cpu核心数)
error_log /var/log/nginx/error.log warn;  # 错误日志
pid /var/run/nginx.pid;     # pid文件
worker_rlimit_nofile 65535; # 文件描述符限制

2. 事件模块(events context)

events {
    worker_connections 1024;      # 每个worker最大连接数
    use epoll;                    # 事件驱动模型(linux)
    multi_accept on;              # 同时接受多个连接
    accept_mutex off;             # 连接互斥锁
}

3. http模块(http context)

基础配置:

http {
    include /etc/nginx/mime.types;    # mime类型
    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;                 # 高效文件传输
    tcp_nopush on;               # tcp优化
    tcp_nodelay on;              # 禁用nagle算法
    keepalive_timeout 65;        # 长连接超时
    client_max_body_size 20m;    # 最大上传文件大小
    # gzip压缩
    gzip on;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json;
    # 上游服务器(负载均衡)
    upstream backend {
        server 192.168.1.100:8080 weight=3;
        server 192.168.1.101:8080;
        server 192.168.1.102:8080 backup;
        # 负载均衡策略:轮询(默认)、ip_hash、least_conn
    }
}

4. 虚拟主机(server context)

server {
    listen 80;                    # 监听端口
    listen [::]:80 ipv6only=on;   # ipv6
    server_name example.com www.example.com;  # 域名
    # 根目录和索引
    root /var/www/html;
    index index.html index.htm index.php;
    # 字符集
    charset utf-8;
    # ssl配置(https)
    listen 443 ssl http2;
    ssl_certificate /etc/ssl/cert.pem;
    ssl_certificate_key /etc/ssl/key.pem;
    ssl_protocols tlsv1.2 tlsv1.3;
    ssl_ciphers high:!anull:!md5;
    # 重定向http到https
    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    }
    # 安全头
    add_header x-frame-options "sameorigin";
    add_header x-content-type-options "nosniff";
    add_header x-xss-protection "1; mode=block";
}

5. 位置块(location context)

location / {
    # 匹配所有请求
    try_files $uri $uri/ /index.php?$query_string;
}
# 精确匹配(=)
location = /api {
    # 仅匹配 /api
}
# 正则匹配(~ 区分大小写,~* 不区分)
location ~ \.(jpg|png|gif)$ {
    expires 30d;  # 缓存控制
    add_header cache-control "public, immutable";
}
# 前缀匹配(^~)
location ^~ /static/ {
    # 匹配 /static/ 开头的uri
    alias /var/www/static/;
}
# api代理
location /api/ {
    proxy_pass http://backend;
    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_connect_timeout 30s;
    proxy_read_timeout 30s;
    proxy_send_timeout 30s;
}
# php处理
location ~ \.php$ {
    fastcgi_pass unix:/var/run/php-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param script_filename $document_root$fastcgi_script_name;
    include fastcgi_params;
}

三、高级配置示例

1. 负载均衡

upstream app_cluster {
    least_conn;  # 最少连接数
    server app1.example.com:8080 max_fails=3 fail_timeout=30s;
    server app2.example.com:8080;
    server app3.example.com:8080 down;  # 临时下线
    keepalive 32;  # 连接池
}

2. 缓存代理

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
                 inactive=60m max_size=1g;
location / {
    proxy_cache my_cache;
    proxy_cache_key "$scheme$request_method$host$request_uri";
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 404 1m;
    proxy_cache_use_stale error timeout updating;
}

3. 限流

# 限制连接数
limit_conn_zone $binary_remote_addr zone=perip:10m;
# 限制请求速率
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
location /api/ {
    limit_conn perip 10;     # 每个ip最多10个连接
    limit_req zone=perip burst=20 nodelay;  # 令牌桶算法
}

4. 反向代理websocket

location /ws/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header upgrade $http_upgrade;
    proxy_set_header connection "upgrade";
}

四、配置最佳实践

  1. 安全配置:
# 隐藏nginx版本号
server_tokens off;
# 限制请求方法
if ($request_method !~ ^(get|post|head)$) {
    return 405;
}
# 防止目录遍历
autoindex off;
# 禁用不需要的http方法
location / {
    limit_except get post { deny all; }
}
  1. 性能优化:
# 文件缓存
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
# 缓冲优化
proxy_buffers 8 16k;
proxy_buffer_size 32k;
client_body_buffer_size 128k;
# tcp优化
sendfile_max_chunk 512k;
  1. 日志管理:
# 按天分割日志(在crontab中配置)
access_log /var/log/nginx/access-$(date +%y%m%d).log;
# 排除静态文件日志
location ~* \.(jpg|css|js)$ {
    access_log off;
    log_not_found off;
}

五、调试和测试

# 检查配置语法
nginx -t
# 测试配置并显示解析结果
nginx -t
# 重新加载配置(不中断服务)
nginx -s reload
# 调试特定问题
error_log /var/log/nginx/error.log debug;

六、常用变量

$remote_addr        # 客户端ip
$http_host          # 请求主机头
$request_uri        # 完整请求uri
$args               # 查询参数
$scheme             # 协议(http/https)
$server_name        # 服务器名
$content_length     # 请求体长度
$http_user_agent    # 用户代理
$status             # 响应状态码

七、配置组织建议

/etc/nginx/
├── nginx.conf          # 主配置文件
├── conf.d/             # 通用配置片段
│   ├── gzip.conf
│   ├── security.conf
│   └── proxy.conf
├── sites-available/    # 可用站点配置
│   └── example.com.conf
├── sites-enabled/      # 启用的站点(符号链接)
│   └── example.com.conf -> ../sites-available/example.com.conf
└── snippets/           # 可复用配置块
    └── ssl-params.conf

到此这篇关于nginx 配置示例及核心模块详解的文章就介绍到这了,更多相关nginx配置核心模块内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com