Nginx 安装与配置指南

本文最后更新于 1 分钟前,文中所描述的信息可能已发生改变。

Nginx 是一个高性能的 HTTP 和反向代理服务器,以及 IMAP/POP3 代理服务器。本文将详细介绍 Nginx 的安装过程和基本配置,包括反向代理、负载均衡和 HTTPS 配置。

环境准备

  • 操作系统:Linux(Ubuntu/Debian/CentOS)
  • 最低配置:1 CPU,512MB RAM
  • 硬盘:至少 10GB 可用空间
  • 网络:可访问互联网

Nginx 安装

Ubuntu/Debian 安装

bash
# 更新软件包列表
sudo apt update

# 安装 Nginx
sudo apt install nginx

# 启动 Nginx
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

# 检查 Nginx 状态
sudo systemctl status nginx

CentOS/RHEL 安装

bash
# 安装 EPEL 仓库
sudo yum install epel-release

# 安装 Nginx
sudo yum install nginx

# 启动 Nginx
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

# 检查 Nginx 状态
sudo systemctl status nginx

从源码编译安装(适用于所有 Linux 发行版)

bash
# 安装依赖
sudo apt install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev # Ubuntu/Debian
# 或
sudo yum groupinstall "Development Tools" # CentOS/RHEL
sudo yum install pcre pcre-devel zlib zlib-devel openssl openssl-devel # CentOS/RHEL

# 下载 Nginx 源码
wget http://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0

# 配置、编译和安装
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module
make
sudo make install

# 创建 systemd 服务文件
sudo nano /etc/systemd/system/nginx.service

将以下内容添加到 nginx.service 文件中:

ini
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
bash
# 重新加载 systemd,启动 Nginx
sudo systemctl daemon-reload
sudo systemctl start nginx
sudo systemctl enable nginx

防火墙配置

Ubuntu/Debian

bash
# 允许 HTTP 和 HTTPS 流量
sudo ufw allow 'Nginx Full'

# 或者单独允许 HTTP 和 HTTPS
sudo ufw allow 'Nginx HTTP'
sudo ufw allow 'Nginx HTTPS'

# 检查防火墙状态
sudo ufw status

CentOS/RHEL

bash
# 允许 HTTP 和 HTTPS 流量
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https

# 重新加载防火墙规则
sudo firewall-cmd --reload

# 检查防火墙状态
sudo firewall-cmd --list-services

Nginx 基本配置

Nginx 的主配置文件位置:

  • Ubuntu/Debian: /etc/nginx/nginx.conf
  • CentOS/RHEL: /etc/nginx/nginx.conf
  • 源码安装: /usr/local/nginx/conf/nginx.conf

基本配置结构

nginx
user nginx;                  # 运行 Nginx 的用户
worker_processes auto;       # Nginx 工作进程数,通常设置为 CPU 核心数
error_log /var/log/nginx/error.log warn;  # 错误日志
pid /var/run/nginx.pid;      # 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;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

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

配置静态网站

创建或编辑站点配置文件:

bash
sudo nano /etc/nginx/conf.d/example.com.conf  # 基于包管理器安装
# 或
sudo nano /usr/local/nginx/conf/conf.d/example.com.conf  # 源码安装

添加以下内容:

nginx
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;
    }

    # 自定义错误页面
    error_page 404 /404.html;
    location = /404.html {
        root /var/www/example.com;
        internal;
    }

    # 日志配置
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}

创建网站目录并添加测试页面:

bash
sudo mkdir -p /var/www/example.com
sudo nano /var/www/example.com/index.html

添加简单的 HTML 内容:

html
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to example.com</title>
</head>
<body>
    <h1>Success! Your Nginx server is working!</h1>
</body>
</html>

设置正确的权限:

bash
sudo chown -R nginx:nginx /var/www/example.com  # 适用于 CentOS
# 或
sudo chown -R www-data:www-data /var/www/example.com  # 适用于 Ubuntu/Debian

测试配置并重启 Nginx:

bash
sudo nginx -t
sudo systemctl restart nginx

配置反向代理

编辑网站配置文件,添加反向代理配置:

bash
sudo nano /etc/nginx/conf.d/example.com.conf
nginx
server {
    listen 80;
    server_name example.com www.example.com;

    location / {
        proxy_pass http://localhost:3000;  # 将请求代理到本地 3000 端口
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

这个配置将所有对 example.com 的请求代理到本地运行在 3000 端口上的应用程序(如 Node.js 应用)。

配置负载均衡

编辑配置文件,添加负载均衡配置:

bash
sudo nano /etc/nginx/conf.d/example.com.conf
nginx
# 定义上游服务器
upstream backend {
    server backend1.example.com weight=3;  # 权重为 3
    server backend2.example.com;           # 默认权重为 1
    server backend3.example.com;
    server backup1.example.com backup;     # 备份服务器
}

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

    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Nginx 支持多种负载均衡算法:

  • 轮询(round-robin):默认方式,按时间顺序逐一分配到不同的上游服务器
  • 最少连接(least_conn):将请求分配给连接数最少的服务器
  • IP 哈希(ip_hash):根据客户端 IP 地址分配,保证同一客户端请求总是发送到同一服务器
nginx
upstream backend {
    least_conn;  # 使用最少连接算法
    server backend1.example.com;
    server backend2.example.com;
}

nginx
upstream backend {
    ip_hash;  # 使用 IP 哈希算法
    server backend1.example.com;
    server backend2.example.com;
}

配置 HTTPS

获取 SSL 证书

使用 Let’s Encrypt 获取免费的 SSL 证书:

bash
# 安装 Certbot
sudo apt install certbot python3-certbot-nginx  # Ubuntu/Debian
# 或
sudo yum install certbot python3-certbot-nginx  # CentOS/RHEL

# 获取证书并自动配置 Nginx
sudo certbot --nginx -d example.com -d www.example.com

# 测试自动续期
sudo certbot renew --dry-run

手动配置 HTTPS:

nginx
server {
    listen 80;
    server_name example.com www.example.com;
    
    # 将 HTTP 重定向到 HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;
    
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
    
    # SSL 配置
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;
    
    # 现代兼容性,禁用老旧的不安全加密套件
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # HSTS (63072000 秒 = 2 年)
    add_header Strict-Transport-Security "max-age=63072000" always;
    
    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;
    
    # 网站配置
    root /var/www/example.com;
    index index.html index.htm;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

性能优化

启用 Gzip 压缩

nginx
http {
    # ... 其他配置 ...
    
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_min_length 256;
    gzip_types
        application/atom+xml
        application/javascript
        application/json
        application/ld+json
        application/manifest+json
        application/rss+xml
        application/vnd.geo+json
        application/vnd.ms-fontobject
        application/x-font-ttf
        application/x-web-app-manifest+json
        application/xhtml+xml
        application/xml
        font/opentype
        image/bmp
        image/svg+xml
        image/x-icon
        text/cache-manifest
        text/css
        text/plain
        text/vcard
        text/vnd.rim.location.xloc
        text/vtt
        text/x-component
        text/x-cross-domain-policy;
}

配置浏览器缓存

nginx
server {
    # ... 其他配置 ...
    
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1y;
        add_header Cache-Control "public, max-age=31536000";
    }
}

限制连接数

nginx
http {
    # ... 其他配置 ...
    
    # 限制每个 IP 的连接数
    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
    
    # 限制每个 IP 的请求速率
    limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=10r/s;
    
    server {
        # ... 其他配置 ...
        
        location / {
            # 限制每个 IP 最多 10 个并发连接
            limit_conn conn_limit_per_ip 10;
            
            # 限制每个 IP 每秒最多 10 个请求,允许最多 5 个请求的突发
            limit_req zone=req_limit_per_ip burst=5 nodelay;
            
            # ... 其他配置 ...
        }
    }
}

监控与维护

启用状态页面

编辑配置文件,添加状态页面:

nginx
server {
    # ... 其他配置 ...
    
    location /nginx_status {
        stub_status on;
        access_log off;
        # 只允许内部 IP 访问
        allow 127.0.0.1;
        deny all;
    }
}

日志轮转

使用 logrotate 管理 Nginx 日志:

bash
sudo nano /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 nginx nginx
    sharedscripts
    postrotate
        if [ -f /var/run/nginx.pid ]; then
            kill -USR1 `cat /var/run/nginx.pid`
        fi
    endscript
}

安全加固建议

  1. 隐藏版本信息
nginx
http {
    # ... 其他配置 ...
    
    server_tokens off;
}
  1. 添加安全头
nginx
server {
    # ... 其他配置 ...
    
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-XSS-Protection "1; mode=block";
    add_header Content-Security-Policy "default-src 'self'; script-src 'self'; img-src 'self'; style-src 'self'; font-src 'self';";
}
  1. 限制不需要的 HTTP 方法
nginx
server {
    # ... 其他配置 ...
    
    if ($request_method !~ ^(GET|HEAD|POST)$) {
        return 405;
    }
}
  1. 保护敏感目录
nginx
location ~ /\.(?!well-known) {
    deny all;
}

总结

通过本文介绍的步骤,您已经:

  • 安装了 Nginx 服务器
  • 配置了基本的静态网站服务
  • 学会了设置反向代理和负载均衡
  • 配置了 HTTPS
  • 了解了性能优化和安全加固方法

Nginx 是一个功能强大的 Web 服务器和反向代理服务器,通过合理配置,可以显著提高网站的性能、安全性和可靠性。根据实际需求,选择合适的配置方案,定期更新和维护 Nginx 以保持其安全和高效。

MySQL 主从配置指南
Redis 安装与配置指南:密码设置与持久化