参考资料

  1. Nginx如何设置防篡改?
  2. Nginxallow、deny:IP访问控制模块详细说明以及案例
  3. NginxFastCGI模块配置详细说明以及案例
  4. CGI(Common Gateway Interface,通用网关接口)详细说明以及案例
  5. Nginx的负载均衡能力
  6. 如何配置Nginx用户认证?
  7. nginx -p详细说明以及案例
  8. Nginx日志记录配置指令详细说明以及案例
# 全局块:配置影响nginx全局的指令
user nginx;                       # 运行用户
worker_processes auto;            # 工作进程数(通常设为CPU核心数)
error_log /var/log/nginx/error.log; # 错误日志路径
pid /run/nginx.pid;               # 进程ID文件路径

# events块:配置网络连接参数
events {
    worker_connections 1024;     # 单个工作进程最大连接数
    use epoll;                   # 事件驱动模型(Linux推荐)
    multi_accept on;             # 同时接受多个连接
}

# http块:配置HTTP服务器参数
http {
    include mime.types;          # 包含MIME类型文件
    default_type application/octet-stream; # 默认MIME类型
    sendfile on;                 # 启用高效文件传输模式
    keepalive_timeout 65;        # 保持连接超时时间(秒)

    # 日志格式定义
    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; # 访问日志路径

    # Server块:配置虚拟主机
    server {
        listen 80;               # 监听端口
        server_name example.com; # 域名/主机名
        root /var/www/html;       # 网站根目录
        index index.html;         # 默认索引文件

        # Location块:配置请求处理规则
        location / {
            try_files $uri $uri/ =404; # 文件查找规则
        }

        location /api/ {
            proxy_pass http://backend; # 反向代理到后端服务器
            proxy_set_header Host $host;
        }

        error_page 404 /404.html;     # 自定义404页面
        error_page 500 502 503 504 /50x.html;
    }

    # 负载均衡配置示例
    upstream backend {
        server 192.168.1.100:8080 weight=5;
        server 192.168.1.101:8080;
        keepalive 32;
    }

    # 包含其他配置文件
    include /etc/nginx/conf.d/*.conf;
}

# 常用指令说明:
# 1. 静态资源服务:
#    root /path/to/files;
#    expires 30d;          # 缓存控制

# 2. SSL配置:
#    listen 443 ssl;
#    ssl_certificate /path/to/cert.pem;
#    ssl_certificate_key /path/to/key.pem;

# 3. 重定向配置:
#    return 301 https://$host$request_uri;

# 4. 访问控制:
#    allow 192.168.1.0/24;
#    deny all;

# 5. Gzip压缩:
#    gzip on;
#    gzip_types text/plain application/json;

# 配置检查命令:
# nginx -t                  # 测试配置文件语法
# nginx -s reload           # 重新加载配置