第11课:Web服务器配置

【腾讯云】语音识别准确率高,支持多语种,多场景,限时特惠,最低14.9元起

推广

【腾讯云】语音识别准确率高,支持多语种,多场景,限时特惠,最低14.9元起

Web服务器配置

Apache HTTP服务器

1. Apache安装

Ubuntu/Debian系统

# 更新包列表
sudo apt update

# 安装Apache
sudo apt install apache2 -y

# 启动并启用Apache
sudo systemctl start apache2
sudo systemctl enable apache2

# 检查状态
sudo systemctl status apache2

CentOS/RHEL系统

# 安装Apache
sudo yum install httpd -y      # CentOS 7
sudo dnf install httpd -y      # CentOS 8+

# 启动并启用Apache
sudo systemctl start httpd
sudo systemctl enable httpd

# 配置防火墙
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

2. Apache基本配置

主配置文件

# Ubuntu/Debian配置文件位置
/etc/apache2/apache2.conf      # 主配置文件
/etc/apache2/sites-available/  # 虚拟主机配置
/etc/apache2/sites-enabled/    # 启用的站点
/etc/apache2/mods-available/   # 可用模块
/etc/apache2/mods-enabled/     # 启用的模块

# CentOS/RHEL配置文件位置
/etc/httpd/conf/httpd.conf     # 主配置文件
/etc/httpd/conf.d/             # 额外配置文件

基本配置示例

# 编辑主配置文件
sudo nano /etc/apache2/apache2.conf

# 重要配置项
ServerRoot /etc/apache2
Listen 80
User www-data
Group www-data
DocumentRoot /var/www/html
DirectoryIndex index.html index.php

# 目录权限配置
<Directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

3. Apache虚拟主机

创建虚拟主机

# 创建站点目录
sudo mkdir -p /var/www/example.com/html
sudo chown -R www-data:www-data /var/www/example.com/html
sudo chmod -R 755 /var/www/example.com

# 创建测试页面
echo "<h1>Welcome to example.com</h1>" | sudo tee /var/www/example.com/html/index.html

# 创建虚拟主机配置
sudo nano /etc/apache2/sites-available/example.com.conf

虚拟主机配置文件

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/html
    
    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
    
    <Directory /var/www/example.com/html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

启用站点

# 启用站点
sudo a2ensite example.com.conf

# 禁用默认站点
sudo a2dissite 000-default.conf

# 测试配置
sudo apache2ctl configtest

# 重新加载配置
sudo systemctl reload apache2

4. Apache模块管理

常用模块

# 启用模块
sudo a2enmod rewrite          # URL重写模块
sudo a2enmod ssl              # SSL模块
sudo a2enmod headers          # HTTP头模块
sudo a2enmod expires          # 过期控制模块

# 禁用模块
sudo a2dismod autoindex       # 禁用目录索引

# 查看已启用模块
apache2ctl -M

# 重启Apache应用模块
sudo systemctl restart apache2

Nginx Web服务器

1. Nginx安装

Ubuntu/Debian系统

# 安装Nginx
sudo apt update
sudo apt install nginx -y

# 启动并启用Nginx
sudo systemctl start nginx
sudo systemctl enable nginx

# 检查状态
sudo systemctl status nginx

CentOS/RHEL系统

# 安装Nginx
sudo yum install nginx -y      # CentOS 7
sudo dnf install nginx -y      # CentOS 8+

# 启动并启用Nginx
sudo systemctl start nginx
sudo systemctl enable nginx

# 配置防火墙
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

2. Nginx基本配置

配置文件结构

# 主配置文件
/etc/nginx/nginx.conf

# 站点配置目录
/etc/nginx/sites-available/    # Ubuntu/Debian
/etc/nginx/sites-enabled/      # Ubuntu/Debian
/etc/nginx/conf.d/             # CentOS/RHEL

# 日志文件
/var/log/nginx/access.log
/var/log/nginx/error.log

主配置文件示例

# /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
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;
    error_log /var/log/nginx/error.log;
    
    # 性能优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    
    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript 
               application/javascript application/xml+rss application/json;
    
    # 包含站点配置
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

3. Nginx虚拟主机

创建站点配置

# 创建站点目录
sudo mkdir -p /var/www/example.com/html
sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www/example.com

# 创建测试页面
echo "<h1>Welcome to example.com - Nginx</h1>" | sudo tee /var/www/example.com/html/index.html

# 创建站点配置文件
sudo nano /etc/nginx/sites-available/example.com

站点配置文件

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    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;
    }
    
    # PHP处理 (如果需要)
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    }
    
    # 静态文件缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # 安全配置
    location ~ /\.ht {
        deny all;
    }
}

启用站点

# 创建符号链接启用站点
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# 测试配置
sudo nginx -t

# 重新加载配置
sudo systemctl reload nginx

SSL/TLS配置

1. Let’s Encrypt免费证书

安装Certbot

# Ubuntu/Debian
sudo apt install certbot python3-certbot-apache python3-certbot-nginx

# CentOS/RHEL
sudo yum install certbot python3-certbot-apache python3-certbot-nginx

Apache SSL配置

# 获取证书
sudo certbot --apache -d example.com -d www.example.com

# 自动续期
sudo crontab -e
# 添加以下行
0 12 * * * /usr/bin/certbot renew --quiet

Nginx SSL配置

# 获取证书
sudo certbot --nginx -d example.com -d www.example.com

# 手动配置Nginx SSL
sudo nano /etc/nginx/sites-available/example.com

Nginx SSL配置示例

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

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    index index.html index.htm index.php;
    
    # SSL证书配置
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
    # SSL安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    
    # 安全头
    add_header Strict-Transport-Security "max-age=63072000" always;
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

2. 自签名证书

创建自签名证书

# 创建证书目录
sudo mkdir -p /etc/ssl/private

# 生成私钥
sudo openssl genrsa -out /etc/ssl/private/example.com.key 2048

# 生成证书签名请求
sudo openssl req -new -key /etc/ssl/private/example.com.key -out /etc/ssl/certs/example.com.csr

# 生成自签名证书
sudo openssl x509 -req -days 365 -in /etc/ssl/certs/example.com.csr -signkey /etc/ssl/private/example.com.key -out /etc/ssl/certs/example.com.crt

# 设置权限
sudo chmod 600 /etc/ssl/private/example.com.key
sudo chmod 644 /etc/ssl/certs/example.com.crt

性能优化

1. Apache性能优化

MPM配置

# 编辑配置文件
sudo nano /etc/apache2/mods-available/mpm_prefork.conf

<IfModule mpm_prefork_module>
    StartServers             8
    MinSpareServers          5
    MaxSpareServers         20
    ServerLimit            256
    MaxRequestWorkers      256
    MaxConnectionsPerChild   0
</IfModule>

启用缓存模块

# 启用缓存模块
sudo a2enmod cache
sudo a2enmod cache_disk
sudo a2enmod expires
sudo a2enmod headers

# 配置缓存
sudo nano /etc/apache2/conf-available/cache.conf

2. Nginx性能优化

工作进程优化

# 优化worker进程
worker_processes auto;
worker_connections 1024;
worker_rlimit_nofile 2048;

# 启用sendfile
sendfile on;
tcp_nopush on;
tcp_nodelay on;

# 连接保持
keepalive_timeout 65;
keepalive_requests 100;

# 缓冲区优化
client_body_buffer_size 128k;
client_max_body_size 10m;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;

缓存配置

# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|txt)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    add_header Vary Accept-Encoding;
    access_log off;
}

# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/javascript
    application/xml+rss
    application/json;

日志管理

1. 日志配置

Apache日志配置

# 自定义日志格式
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common

# 虚拟主机日志
<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/example.com/html
    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>

Nginx日志配置

# 自定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';

log_format detailed '$remote_addr - $remote_user [$time_local] "$request" '
                   '$status $body_bytes_sent "$http_referer" '
                   '"$http_user_agent" $request_time $upstream_response_time';

# 服务器块日志
server {
    access_log /var/log/nginx/example.com.access.log main;
    error_log /var/log/nginx/example.com.error.log;
}

2. 日志轮转

配置logrotate

# Apache日志轮转
sudo nano /etc/logrotate.d/apache2

/var/log/apache2/*.log {
    daily
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 644 root adm
    sharedscripts
    postrotate
        systemctl reload apache2
    endscript
}

# Nginx日志轮转
sudo nano /etc/logrotate.d/nginx

/var/log/nginx/*.log {
    daily
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 644 www-data adm
    sharedscripts
    postrotate
        systemctl reload nginx
    endscript
}

安全配置

1. 基本安全措施

隐藏服务器信息

# Apache安全配置
ServerTokens Prod
ServerSignature Off
# Nginx安全配置
server_tokens off;

防止目录遍历

# Apache配置
<Directory /var/www/html>
    Options -Indexes
</Directory>
# Nginx配置
autoindex off;

2. 访问控制

IP访问控制

# Apache IP限制
<Directory /var/www/html/admin>
    Require ip 192.168.1.0/24
    Require ip 10.0.0.1
</Directory>
# Nginx IP限制
location /admin {
    allow 192.168.1.0/24;
    allow 10.0.0.1;
    deny all;
}

总结

Web服务器配置要点:

  1. 服务器选择:Apache适合传统应用,Nginx适合高并发场景
  2. 虚拟主机:合理配置虚拟主机,支持多站点部署
  3. SSL配置:启用HTTPS,保证数据传输安全
  4. 性能优化:调整服务器参数,提高处理能力
  5. 日志管理:配置日志记录和轮转,便于监控分析
  6. 安全加固:实施安全措施,防范常见攻击

下一课预告

在下一课中,我们将学习数据库安装与管理,包括:

  • MySQL/MariaDB安装配置
  • PostgreSQL安装配置
  • 数据库安全设置
  • 备份恢复策略

💡 小贴士:Web服务器是现代应用的基础设施。建议根据实际需求选择合适的服务器,并定期更新和优化配置以确保最佳性能和安全性。

Vue3 + TypeScript 企业级项目实战

课程推荐

Vue3 + TypeScript 企业级项目实战
Python 全栈开发工程师培训

热门课程

Python 全栈开发工程师培训

📚 文章对你有帮助?请关注我的公众号,万分感谢!

获取更多优质技术文章,第一时间掌握最新技术动态

关注公众号

关注公众号

第一时间获取最新技术文章

添加微信

添加微信

技术交流 · 问题答疑 · 学习指导

评论讨论

欢迎留下你的想法和建议