Nginx 基本使用和高级用法详解

目录

  • [Nginx 基本使用和高级用法详解](#Nginx 基本使用和高级用法详解)
    • [一、Nginx 简介](#一、Nginx 简介)
    • 二、基本安装与使用
    • 三、配置文件结构
      • [1. 主要配置文件目录结构](#1. 主要配置文件目录结构)
      • [2. 基本配置示例(`/etc/nginx/nginx.conf`)](#2. 基本配置示例(/etc/nginx/nginx.conf))
    • 四、虚拟主机配置
      • [1. 基本虚拟主机配置](#1. 基本虚拟主机配置)
      • [2. 启用站点](#2. 启用站点)
    • 五、高级配置技巧
      • [1. 反向代理配置](#1. 反向代理配置)
      • [2. 负载均衡](#2. 负载均衡)
      • [3. SSL/TLS 配置](#3. SSL/TLS 配置)
      • [4. 缓存配置](#4. 缓存配置)
      • [5. 安全配置](#5. 安全配置)
      • [6. 限流配置](#6. 限流配置)
      • [7. URL 重写和重定向](#7. URL 重写和重定向)
      • [8. Gzip 压缩](#8. Gzip 压缩)
    • 六、性能优化配置
      • [1. 连接优化](#1. 连接优化)
      • [2. 工作进程优化](#2. 工作进程优化)
    • 七、日志配置
      • [1. 自定义日志格式](#1. 自定义日志格式)
      • [2. 日志分割脚本(`rotate_nginx_logs.sh`)](#2. 日志分割脚本(rotate_nginx_logs.sh))
    • 八、监控和调试
      • [1. 状态页面配置](#1. 状态页面配置)
      • [2. 调试常用命令](#2. 调试常用命令)
    • [九、Docker 中的 Nginx](#九、Docker 中的 Nginx)
      • [1. Dockerfile 示例](#1. Dockerfile 示例)
      • [2. Docker Compose 示例](#2. Docker Compose 示例)
    • 结语

Nginx 基本使用和高级用法详解

一、Nginx 简介

Nginx 是一个高性能的 HTTP 和反向代理服务器,具有占用内存少、并发能力强等特点,广泛应用于 Web 服务、负载均衡、静态资源处理和反向代理等场景。

二、基本安装与使用

1. 安装 Nginx

Ubuntu/Debian
bash 复制代码
sudo apt update
sudo apt install nginx
CentOS/RHEL
bash 复制代码
sudo yum install nginx
# 或
sudo dnf install nginx

2. 基本操作命令

bash 复制代码
# 启动
sudo systemctl start nginx

# 停止
sudo systemctl stop nginx

# 重启
sudo systemctl restart nginx

# 重新加载配置(不中断服务)
sudo systemctl reload nginx

# 查看状态
sudo systemctl status nginx

# 开机自启
sudo systemctl enable nginx

三、配置文件结构

1. 主要配置文件目录结构

复制代码
/etc/nginx/
├── nginx.conf              # 主配置文件
├── conf.d/                 # 额外配置文件目录
├── sites-available/        # 可用站点配置文件
└── sites-enabled/          # 已启用站点配置文件(软链接指向 sites-available)

2. 基本配置示例(/etc/nginx/nginx.conf

nginx 复制代码
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

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;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

四、虚拟主机配置

1. 基本虚拟主机配置

nginx 复制代码
# /etc/nginx/sites-available/example.com

server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/example.com;
    index index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    # 静态资源缓存优化
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

2. 启用站点

bash 复制代码
# 创建软链接启用站点
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# 测试配置是否正确
sudo nginx -t

# 重新加载配置
sudo systemctl reload nginx

五、高级配置技巧

1. 反向代理配置

nginx 复制代码
server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://localhost:3000;
        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;

        # 超时设置
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;

        # 缓冲设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }
}

2. 负载均衡

nginx 复制代码
upstream backend {
    server backend1.example.com weight=3;
    server backend2.example.com;
    server backend3.example.com;
    server backup.example.com backup;
}

server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

3. SSL/TLS 配置

nginx 复制代码
server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;

    # SSL 安全设置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # HSTS 强制 HTTPS
    add_header Strict-Transport-Security "max-age=63072000" always;

    root /var/www/example.com;
    index index.html;
}

4. 缓存配置

代理缓存
nginx 复制代码
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g 
                 inactive=60m use_temp_path=off;

server {
    location / {
        proxy_cache my_cache;
        proxy_pass http://backend;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        add_header X-Cache-Status $upstream_cache_status;
    }
}
静态资源缓存
nginx 复制代码
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

5. 安全配置

nginx 复制代码
# 隐藏版本号
server_tokens off;

# 安全响应头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

# 上传大小限制
client_max_body_size 10m;

# 限制非法请求方法
if ($request_method !~ ^(GET|POST|HEAD)$) {
    return 405;
}

6. 限流配置

nginx 复制代码
# 定义限流区域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=2r/m;

server {
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://backend;
    }

    location /login {
        limit_req zone=login burst=5;
        proxy_pass http://backend;
    }
}

7. URL 重写和重定向

nginx 复制代码
server {
    # 强制跳转 HTTPS
    if ($scheme = http) {
        return 301 https://$server_name$request_uri;
    }

    # 路径重定向
    location /old-path {
        return 301 /new-path;
    }

    # 去除 .html 扩展名
    location / {
        try_files $uri $uri.html $uri/ =404;
    }

    # RESTful URL 重写
    location /api/v1/users {
        rewrite ^/api/v1/users/(.*)$ /api/v1/users?id=$1 last;
    }
}

8. Gzip 压缩

nginx 复制代码
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/json
    application/javascript
    application/xml+rss
    application/atom+xml
    image/svg+xml;

六、性能优化配置

1. 连接优化

nginx 复制代码
events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 1000;

    # 文件描述符缓存
    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
}

2. 工作进程优化

nginx 复制代码
worker_processes auto;
worker_cpu_affinity auto;

# 提高文件描述符限制
worker_rlimit_nofile 65535;

七、日志配置

1. 自定义日志格式

nginx 复制代码
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for" '
                'rt=$request_time uct="$upstream_connect_time" '
                'uht="$upstream_header_time" urt="$upstream_response_time"';

access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;

2. 日志分割脚本(rotate_nginx_logs.sh

bash 复制代码
#!/bin/bash
# rotate_nginx_logs.sh

LOG_DIR="/var/log/nginx"
DATE=$(date -d "yesterday" +%Y-%m-%d)

mv $LOG_DIR/access.log $LOG_DIR/access.$DATE.log
mv $LOG_DIR/error.log $LOG_DIR/error.$DATE.log

# 通知 Nginx 重新打开日志文件
kill -USR1 $(cat /var/run/nginx.pid)

# 压缩7天前的日志
find $LOG_DIR -name "*.log" -mtime +7 -exec gzip {} \;

提示 :可配合 cron 定时执行日志轮转。

八、监控和调试

1. 状态页面配置

nginx 复制代码
server {
    listen 8080;
    server_name localhost;

    location /nginx_status {
        stub_status on;
        access_log off;
        allow 127.0.0.1;
        deny all;
    }
}

访问 http://localhost:8080/nginx_status 可查看连接状态。

2. 调试常用命令

bash 复制代码
# 测试配置语法
sudo nginx -t

# 打印完整配置(含 include)
sudo nginx -T

# 查看 Nginx 编译参数和模块
nginx -V

# 实时查看日志
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

# 压力测试(Apache Bench)
ab -n 1000 -c 100 http://example.com/

九、Docker 中的 Nginx

1. Dockerfile 示例

dockerfile 复制代码
FROM nginx:alpine

COPY nginx.conf /etc/nginx/nginx.conf
COPY sites/ /etc/nginx/sites-available/
COPY html/ /usr/share/nginx/html/

RUN ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

EXPOSE 80 443

CMD ["nginx", "-g", "daemon off;"]

2. Docker Compose 示例

yaml 复制代码
version: '3.8'
services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./sites:/etc/nginx/sites-available
      - ./html:/usr/share/nginx/html
      - ./ssl:/etc/ssl
    networks:
      - webnet

networks:
  webnet:
    driver: bridge

结语

本指南涵盖了 Nginx 的 基础安装、虚拟主机、反向代理、负载均衡、SSL 配置、缓存、安全加固、限流、URL 重写、Gzip 压缩、性能调优、日志管理、监控调试 以及 Docker 部署 等核心内容,适用于构建高可用、高性能、安全的 Web 服务架构。

建议在生产环境中结合具体业务场景进行配置优化,并定期审查安全策略和性能指标。

相关推荐
wangjialelele3 小时前
端口号、常见协议和套接字
linux·运维·服务器·c语言·网络
蜜蜜不吃糖4 小时前
ESXI主机重置带外密码
linux·运维·服务器
幸运小圣4 小时前
Iterator迭代器 【ES6】
开发语言·javascript·es6
葱头的故事4 小时前
将传给后端的数据转换为以formData的类型传递
开发语言·前端·javascript
中微子4 小时前
🚀 2025前端面试必考:手把手教你搞定自定义右键菜单,告别复制失败的尴尬
javascript·面试
智象科技4 小时前
CMDB报表体系如何驱动智能运维
大数据·运维·报表·一体化运维·cmdb
高光视点4 小时前
伊萨推出升级版SUPRAREX™ PRO自动化切割设备:更大尺寸、更强结构、更高安全性、更易维护
运维·自动化
b***25114 小时前
深圳比斯特自动化|圆柱电池测试设备核心功能与技术发展解析
运维·自动化
King's King4 小时前
自动化仓库总体设计
运维·自动化