基础操作

本指南将帮助您快速上手 Nginx,了解其基本概念和配置方法。

什么是 Nginx?

Nginx 是一个高性能的 HTTP 和反向代理 Web 服务器,同时也提供了 IMAP/POP3/SMTP 服务。

主要特性

  • 高性能:处理大量并发连接
  • 低内存占用:高效的事件驱动架构
  • 反向代理:负载均衡和缓存
  • 静态文件服务:快速提供静态内容
  • SSL/TLS 支持:HTTPS 加密
  • HTTP/2 支持:提升性能
  • 模块化设计:丰富的扩展模块

应用场景

  • Web 服务器
  • 反向代理服务器
  • 负载均衡器
  • API 网关
  • CDN 边缘节点
  • 流媒体服务器

安装 Nginx

如果尚未安装 Nginx,请参考:

快速开始

1. 启动 Nginx

# Linux/macOS
sudo nginx

# 或使用 systemd
sudo systemctl start nginx

# Windows
nginx.exe

2. 验证运行

# 检查进程
ps aux | grep nginx

# 或使用 curl
curl http://localhost

在浏览器中访问 http://localhost,应该看到 "Welcome to nginx!" 页面。

3. 基本命令

# 启动
nginx

# 停止
nginx -s stop

# 优雅退出
nginx -s quit

# 重新加载配置
nginx -s reload

# 重新打开日志
nginx -s reopen

# 测试配置
nginx -t

# 查看版本
nginx -v

# 查看编译信息
nginx -V

配置文件结构

主配置文件

默认位置:

  • Linux: /etc/nginx/nginx.conf
  • macOS: /usr/local/etc/nginx/nginx.conf
  • Windows: conf/nginx.conf

基本结构

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
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;

    include /etc/nginx/conf.d/*.conf;
}

配置块说明

说明
main全局配置
events事件处理配置
httpHTTP 服务器配置
server虚拟主机配置
locationURL 匹配配置

提供静态内容

基本配置

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

多个网站

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

    location / {
        root   /var/www/example.com;
        index  index.html index.htm;
    }
}

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

    location / {
        root   /var/www/blog;
        index  index.html index.htm;
    }
}

自定义错误页面

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    error_page   404              /404.html;
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

设置代理服务器

基本代理

server {
    listen       80;
    server_name  localhost;

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

负载均衡

upstream backend {
    server backend1.example.com:8080;
    server backend2.example.com:8080;
    server backend3.example.com:8080;
}

server {
    listen       80;
    server_name  localhost;

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

设置 FastCGI 代理

PHP 配置

server {
    listen       80;
    server_name  localhost;

    root   /usr/share/nginx/html;
    index  index.php index.html index.htm;

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

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

常用配置示例

启用 gzip 压缩

http {
    gzip  on;
    gzip_min_length  1000;
    gzip_types       text/plain text/css application/json application/javascript;
}

配置 HTTPS

server {
    listen       443 ssl;
    server_name  localhost;

    ssl_certificate      /etc/ssl/certs/server.crt;
    ssl_certificate_key  /etc/ssl/private/server.key;

    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

重定向到 HTTPS

server {
    listen       80;
    server_name  example.com;
    return 301 https://$host$request_uri;
}

日志管理

访问日志

http {
    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;
}

错误日志

error_log  /var/log/nginx/error.log warn;

日志级别

级别说明
debug调试信息
info一般信息
notice通知信息
warn警告信息
error错误信息
crit严重错误
alert需要立即处理
emerg系统不可用

性能优化

调整工作进程

user  nginx;
worker_processes  auto;  # 自动检测 CPU 核心数

调整连接数

events {
    worker_connections  2048;
}

启用 sendfile

http {
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
}

调整缓冲区

http {
    client_body_buffer_size  128k;
    client_max_body_size     10m;
    client_header_buffer_size  1k;
    large_client_header_buffers  4 4k;
    output_buffers   1 32k;
    postpone_output  1460;
}

安全配置

隐藏版本号

http {
    server_tokens off;
}

限制请求方法

server {
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }
}

限制访问速度

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    server {
        limit_req zone=one burst=5;
    }
}

故障排查

查看日志

# 错误日志
sudo tail -f /var/log/nginx/error.log

# 访问日志
sudo tail -f /var/log/nginx/access.log

测试配置

sudo nginx -t

检查端口

sudo netstat -tlnp | grep :80
# 或
sudo ss -tlnp | grep :80

检查进程

ps aux | grep nginx