Web服务部署指南

Web服务器选择

Nginx vs Apache对比

特性NginxApache
架构事件驱动,异步非阻塞进程驱动,同步阻塞
性能高并发,低内存占用稳定性好,模块丰富
配置复杂度相对简单功能强大但配置复杂
模块系统静态编译动态加载
适用场景静态内容,反向代理动态内容,.htaccess

Nginx部署实战

安装Nginx

# Ubuntu/Debian
sudo apt update
sudo apt install nginx
 
# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx
 
# 启动服务
sudo systemctl start nginx
sudo systemctl enable nginx

Nginx配置文件结构

/etc/nginx/
├── nginx.conf              # 主配置文件
├── sites-available/        # 可用站点配置
├── sites-enabled/          # 启用站点配置
├── conf.d/                 # 附加配置片段
└── modules-available/      # 可用模块

基础配置示例

# /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 index.php;
 
    # 日志配置
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
 
    # 静态文件处理
    location / {
        try_files $uri $uri/ =404;
    }
 
    # 图片缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
 
    # PHP处理
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
 
    # 安全设置
    location ~ /\. {
        deny all;
    }
}

启用站点

# 创建软链接启用站点
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
 
# 测试配置
sudo nginx -t
 
# 重载配置
sudo systemctl reload nginx

Apache部署实战

安装Apache

# Ubuntu/Debian
sudo apt install apache2
 
# CentOS/RHEL  
sudo yum install httpd
 
# 启动服务
sudo systemctl start apache2  # Ubuntu
sudo systemctl start httpd    # CentOS

Apache配置文件

/etc/apache2/               # Ubuntu/Debian
├── apache2.conf           # 主配置文件
├── sites-available/       # 可用站点
├── sites-enabled/         # 启用站点
├── mods-available/        # 可用模块
├── mods-enabled/          # 启用模块
└── conf-available/        # 可用配置

/etc/httpd/                 # CentOS/RHEL
├── conf/httpd.conf        # 主配置文件
├── conf.d/                # 附加配置
└── conf.modules.d/        # 模块配置

虚拟主机配置

# /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com
    
    # 日志配置
    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
    
    # 目录权限
    <Directory /var/www/example.com>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    # PHP支持
    <FilesMatch "\.php$">
        SetHandler application/x-httpd-php
    </FilesMatch>
</VirtualHost>

SSL/TLS证书配置

Let’s Encrypt免费证书

# 安装Certbot
sudo apt install certbot python3-certbot-nginx  # Nginx
sudo apt install certbot python3-certbot-apache # Apache
 
# 获取证书
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot --apache -d example.com -d www.example.com
 
# 自动续期测试
sudo certbot renew --dry-run

手动SSL配置

# Nginx SSL配置
server {
    listen 443 ssl http2;
    server_name example.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/private.key;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # HSTS
    add_header Strict-Transport-Security "max-age=63072000" always;
    
    root /var/www/example.com;
    index index.html;
}
 
# HTTP重定向到HTTPS
server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

反向代理配置

Nginx反向代理

server {
    listen 80;
    server_name api.example.com;
    
    location / {
        proxy_pass http://127.0.0.1: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;
    }
}

负载均衡配置

upstream backend {
    least_conn;  # 最少连接算法
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080 weight=2;
    server 192.168.1.12:8080 weight=1 max_fails=3 fail_timeout=30s;
    
    # 健康检查
    keepalive 32;
}
 
server {
    listen 80;
    server_name app.example.com;
    
    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

性能优化

Nginx性能调优

# nginx.conf全局配置
worker_processes auto;                    # 根据CPU核心数自动设置
worker_connections 1024;                  # 每个worker的连接数
use epoll;                                # Linux高效事件模型
 
# HTTP模块配置
http {
    sendfile on;                          # 零拷贝传输
    tcp_nopush on;                        # 优化数据包发送
    tcp_nodelay on;                       # 禁用Nagle算法
    keepalive_timeout 65;                 # 保持连接超时
    
    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1000;
    gzip_types text/plain text/css application/json application/javascript;
    
    # 缓存配置
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
}

安全加固

# 安全头部
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
 
# 限制访问
location /admin {
    allow 192.168.1.0/24;
    deny all;
    
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
 
# 限速配置
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req zone=api burst=20 nodelay;
 
# 文件上传限制
client_max_body_size 10M;

日志分析

日志格式配置

# 自定义日志格式
log_format detailed '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent" '
                   '$request_time $upstream_response_time';
 
access_log /var/log/nginx/access.log detailed;

日志分析工具

# 统计访问最多的IP
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -20
 
# 统计访问最多的URL
awk '{print $7}' access.log | sort | uniq -c | sort -nr | head -20
 
# 统计状态码分布
awk '{print $9}' access.log | sort | uniq -c | sort -nr
 
# 响应时间分析
awk '{print $NF}' access.log | sort -n | tail -20

💡 部署建议:

  • 生产环境优先选择Nginx作为前端服务器
  • 使用SSL证书保障数据传输安全
  • 配置适当的缓存和压缩提升性能
  • 定期监控和分析访问日志

🔗 相关笔记: 02.04_网络管理 08.02_数据库部署 11.01_性能优化