Nginx 与 Apache 配置详解
概述
Nginx 和 Apache HTTP Server 是当今最主流的两款 Web 服务器软件。本文从核心概念、配置实践、性能对比和安全加固等维度进行系统性介绍。
一、Nginx 核心概念
1.1 进程模型
Nginx 采用 master/worker 多进程模型,具有高度的并发处理能力和稳定的运行时架构。
- master 进程:负责读取和验证配置文件、管理 worker 进程(启动、停止、平滑重载)、处理非 HTTP 请求(如信号管理)。master 进程以 root 用户运行,绑定特权端口(如 80、443)。
- worker 进程:实际处理客户端请求的进程。每个 worker 进程以非 root 用户运行(通过
user指令指定),采用事件驱动和异步非阻塞 I/O 模型,单进程即可处理数万并发连接。worker 进程数量通常设置为等于 CPU 核心数。 - cache loader / cache manager:负责磁盘缓存加载和过期清理的辅助进程。
信号控制示例:
- nginx -s reload → master 向 worker 发送 HUP 信号,平滑重载配置
- nginx -s quit → 优雅退出,处理完当前连接后关闭
- nginx -s stop → 强制停止1.2 配置文件结构
Nginx 配置文件通常位于 /etc/nginx/nginx.conf,采用层级化的指令块结构:
main 层(全局配置)
├── events 块(事件驱动配置)
└── http 块(HTTP 服务配置)
├── upstream 块(负载均衡组)
├── server 块(虚拟主机)
│ ├── location 块(URI 匹配与处理规则)
│ └── ...
└── ...- main 层:包括
worker_processes、user、error_log、pid等全局指令。 - events 块:配置
worker_connections(单 worker 最大连接数)、use epoll(Linux 高效事件驱动)等。 - http 块:包含所有 HTTP 相关的配置,如
include mime.types、sendfile、keepalive_timeout等。 - server 块:定义虚拟主机,每个 server 块绑定特定域名和端口。
- location 块:匹配请求 URI 并执行对应的处理规则(反向代理、静态文件、重写等)。
二、Nginx 核心配置详解
2.1 server 配置
server 块定义虚拟主机,通过 listen 绑定端口,通过 server_name 匹配域名。
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
# 默认 server 处理未匹配的请求
# listen 80 default_server;
charset utf-8;
access_log /var/log/nginx/example_access.log;
error_log /var/log/nginx/example_error.log warn;
}server_name支持精确匹配、通配符(*.example.com)和正则(~^www\d+\.example\.com$)。- 多个 server 匹配时优先级:精确匹配 > 通配符前缀 > 通配符后缀 > 正则 > default_server。
2.2 location 配置
location 指令用于匹配请求 URI,支持前缀匹配和正则匹配两种方式。
server {
# 前缀匹配(默认行为)
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
# 精确匹配(=)
location = /favicon.ico {
log_not_found off;
access_log off;
}
# 路径前缀匹配(^~,匹配后不再检查正则)
location ^~ /static/ {
alias /data/static/;
}
# 正则匹配(~ 区分大小写,~* 不区分大小写)
location ~ \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
access_log off;
}
location ~* \.(mp4|webm)$ {
mp4;
mp4_buffer_size 4M;
mp4_max_buffer_size 10M;
}
}location 匹配优先级规则:
- 先匹配所有前缀 location,记录最长匹配的
^~和普通前缀。 - 检查精确匹配(
=),命中则立即使用。 - 检查
^~前缀匹配,命中则不再检查正则。 - 按配置文件顺序检查正则匹配(
~/~*),命中则立即使用。 - 使用最长匹配的普通前缀 location。
2.3 反向代理 proxy_pass
反向代理是 Nginx 最常见的用途之一,将客户端请求转发到后端服务。
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:8080;
# 传递客户端真实信息
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 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 缓冲区配置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
# 禁用 1.0 默认的 keepalive
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}proxy_pass 带 URI 和不带 URI 的区别:
- 不带 URI:
proxy_pass http://backend;—— 完整传递原始 URI。 - 带 URI:
proxy_pass http://backend/api/;—— 用/api/替换 location 匹配部分。
# 示例:替换路径前缀
location /api/ {
proxy_pass http://backend:8080/; # /api/users → /users
}
location /api/ {
proxy_pass http://backend:8080; # /api/users → /api/users
}2.4 负载均衡 upstream
upstream 定义一组后端服务器,Nginx 支持多种负载均衡算法。
upstream backend {
# 默认轮询(round-robin)
server 192.168.1.10:8080 weight=3 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 backup; # 备用服务器
# 保持长连接
keepalive 32;
}支持的负载均衡算法:
| 算法 | 指令 | 说明 |
|---|---|---|
| 轮询 | (默认) | 按权重依次分配请求,默认权重均为 1 |
| 最少连接 | least_conn | 分配到当前活跃连接数最少的服务器 |
| IP 哈希 | ip_hash | 同一客户端 IP 始终分配到同一台服务器,用于 session 粘滞 |
| 通用哈希 | hash $request_uri consistent | 基于自定义 key 哈希,consistent 启用一致性哈希 |
| 随机 | random two least_conn | 随机选择两台,再选连接数较少的一台 |
upstream ws_backend {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
upstream api_gateway {
least_conn;
server 10.0.0.1:3000 max_conns=100;
server 10.0.0.2:3000 max_conns=100;
}2.5 HTTPS 配置
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.pem;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
# 协议与加密套件
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;
ssl_prefer_server_ciphers on;
# DH 参数(提升 DHE 密钥交换安全性)
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
# 会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 1.1.1.1 valid=300s;
resolver_timeout 5s;
# HSTS(HTTP Strict Transport Security)
add_header Strict-Transport-Security "max-age=63072000" always;
# HTTP → HTTPS 跳转
error_page 497 https://$host$request_uri;
}
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}2.6 HTTP/2
在 HTTPS 配置中启用 http2(如上例 listen 443 ssl http2;),即可开启 HTTP/2 支持。HTTP/2 的核心优势:
- 多路复用:单个连接上同时传输多个请求/响应,消除队头阻塞。
- 头部压缩:HPACK 算法压缩请求和响应头部,减少传输数据量。
- 服务器推送:服务器可主动推送客户端所需的资源(谨慎使用,实践中容易导致带宽浪费,推荐使用
103 Early Hints替代)。 - 二进制帧:协议以二进制帧格式传输,解析效率高于 HTTP/1.1 的文本格式。
# 服务器推送示例
location / {
http2_push /static/app.js;
http2_push /static/style.css;
}2.7 gzip 压缩
gzip on;
gzip_min_length 1000;
gzip_comp_level 6;
gzip_vary on;
gzip_disable "msie6";
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/xml
application/x-font-ttf
image/svg+xml;
gzip_proxied any;
gzip_buffers 16 8k;gzip_comp_level:1-9,推荐 4-6,压缩比和 CPU 开销的平衡点。gzip_min_length:小于该值的文件不压缩,通常 1000 字节。gzip_static on:配合ngx_http_gzip_static_module,可预生成.gz静态压缩文件,减少实时压缩 CPU 开销。
2.8 静态文件缓存
server {
# Sendfile 系统调用(零拷贝)
sendfile on;
sendfile_max_chunk 1m;
tcp_nopush on; # 配合 sendfile,在发送完响应头后才发送包
tcp_nodelay on; # 禁用 Nagle 算法,减小延迟
# 文件缓存(open_file_cache)
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2?|ttf|eot|svg)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
log_not_found off;
}
location ~* \.(html|htm)$ {
expires 5m;
add_header Cache-Control "public, must-revalidate";
}
}三、Nginx 常见场景配置
3.1 SPA 路由配置
单页应用(如 React、Vue、Angular)使用 History 路由模式时,所有非静态资源请求需回退到 index.html。
server {
listen 80;
server_name app.example.com;
root /var/www/spa/dist;
index index.html;
# 静态资源优先匹配
location /assets/ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# SPA 路由回退
location / {
try_files $uri $uri/ /index.html;
}
# 监控类路径单独处理(不交给 SPA)
location /health {
access_log off;
return 200 "OK";
}
}3.2 WebSocket 代理
location /ws/ {
proxy_pass http://ws_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# WebSocket 长连接超时
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
# 缓冲禁用(WebSocket 不适合缓冲)
proxy_buffering off;
}3.3 限流 limit_req
Nginx 通过 ngx_http_limit_req_module 提供请求限流能力,基于漏桶算法。
http {
# 定义限流区域:10MB 内存空间,请求速率 5r/s(每秒 5 个请求)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;
# 按 URI 进行更细粒度的限流
limit_req_zone $binary_remote_addr$uri zone=per_uri_limit:10m rate=10r/s;
# 连接数限制
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location /api/ {
limit_req zone=api_limit burst=10 nodelay;
# burst=10:允许瞬时超过限制最多 10 个请求排队
# nodelay:排队请求不延迟处理,但超出 burst+rate 的请求直接返回 503
limit_req_status 429;
# 限制单个 IP 最大连接数
limit_conn conn_limit 20;
limit_conn_status 503;
proxy_pass http://backend;
}
# 针对登录接口设置更严格的限流
location /api/login {
limit_req zone=api_limit burst=2 nodelay;
proxy_pass http://backend;
}
}
}3.4 访问控制
server {
# IP 白名单
location /admin/ {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
deny all;
}
# 基础认证
location /private/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
# 请求方法限制
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 405;
}
# User-Agent 过滤
location / {
if ($http_user_agent ~* (curl|wget|scrapy|python-requests)) {
return 403;
}
}
# 防盗链
location ~* \.(jpg|jpeg|png|gif|webp)$ {
valid_referers none blocked server_names
~\.example\.com
~\.google\.com
~\.baidu\.com;
if ($invalid_referer) {
return 403;
}
}
}四、Apache HTTP Server
4.1 MPM 模型
Apache 通过多处理模块(MPM,Multi-Processing Module)管理请求处理,不同的 MPM 适用于不同场景。
| MPM | 模型 | 特点 | 适用场景 |
|---|---|---|---|
| prefork | 进程 | 每个请求一个独立进程,不需要线程安全,稳定可靠 | 兼容老版本 PHP 等非线程安全模块 |
| worker | 线程 | 多进程 + 多线程,每个进程包含多个线程 | 高并发静态服务,资源消耗低于 prefork |
| event | 事件驱动 | 基于 worker 优化,独立处理长连接监听(Event Loop) | 高并发动态请求,推荐现代部署使用 |
prefork 配置示例:
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 10000
</IfModule>worker 配置示例:
<IfModule mpm_worker_module>
StartServers 3
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 10000
</IfModule>event 配置示例(Apache 2.4+ 推荐):
<IfModule mpm_event_module>
StartServers 3
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 10000
</IfModule>4.2 虚拟主机 VirtualHost
Apache 使用 VirtualHost 实现多站点托管。可以基于 IP、端口或域名(Name-based)进行区分。
# 基于域名(Name-based Virtual Host)
NameVirtualHost *:80
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example/public
<Directory /var/www/example/public>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example_error.log
CustomLog ${APACHE_LOG_DIR}/example_access.log combined
</VirtualHost>
<VirtualHost *:80>
ServerName api.example.com
DocumentRoot /var/www/api/public
<Directory /var/www/api/public>
Options -Indexes
AllowOverride All
Require all granted
</Directory>
</VirtualHost>4.3 .htaccess
.htaccess 允许在目录级别覆盖 Apache 配置,无需重启服务器即可生效。在多用户共享主机场景中非常实用。
配置启用(需在 VirtualHost 的 Directory 中设置):
<Directory /var/www/html>
AllowOverride All
</Directory>常见 .htaccess 示例:
# 开启重写引擎
RewriteEngine On
# 禁止目录浏览
Options -Indexes
# 自定义错误页面
ErrorDocument 404 /404.html
ErrorDocument 403 /403.html
ErrorDocument 500 /500.html
# 文件访问保护
<FilesMatch "\.(env|config|sql|log)$">
Require all denied
</FilesMatch>
# 设置默认字符集
AddDefaultCharset UTF-8
# 压缩静态资源
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript application/json
</IfModule>
# 设置缓存过期
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 hour"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
</IfModule>4.4 mod_rewrite
mod_rewrite 是 Apache 最强大的 URL 重写模块,支持基于正则表达式的路径重写。
RewriteEngine On
# 强制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
# 移除 www 前缀
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
# 将请求重写到入口文件(例如 Laravel、WordPress 等框架)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
# 重定向旧 URL 到新 URL
RewriteRule ^old-page/?$ /new-page [R=301,L]
RewriteRule ^product/(\d+)/?$ /product?id=$1 [QSA,L]
# 阻止特定 User-Agent
RewriteCond %{HTTP_USER_AGENT} (curl|wget|scrapy) [NC]
RewriteRule .* - [F,L]4.5 SSL 配置
<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/example/public
# 证书配置
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/example.com.pem
SSLCertificateKeyFile /etc/apache2/ssl/example.com.key
SSLCertificateChainFile /etc/apache2/ssl/chain.pem
# 协议与加密套件
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384
SSLHonorCipherOrder on
# 会话缓存
SSLSessionCache shmcb:/var/cache/apache2/ssl_cache(512000)
SSLSessionCacheTimeout 300
# HSTS
Header always set Strict-Transport-Security "max-age=63072000"
# OCSP Stapling
SSLUseStapling on
SSLStaplingResponderTimeout 5
SSLStaplingReturnResponderErrors off
SSLStaplingCache shmcb:/var/cache/apache2/ssl_stapling(512000)
<Directory /var/www/example/public>
Options -Indexes
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
# HTTP → HTTPS 跳转
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>五、Nginx vs Apache 对比
5.1 性能模型对比
| 维度 | Nginx | Apache |
|---|---|---|
| 并发模型 | 事件驱动、异步非阻塞 I/O | 进程/线程驱动(每种 MPM 不同) |
| 静态文件性能 | 极高,支持 sendfile 零拷贝 | 高,但高并发下资源消耗更大 |
| 动态内容 | 通过反向代理转发(自身不处理) | 可直接嵌入 mod_php、mod_wsgi 等模块 |
| 内存占用 | 低,连接越多优势越明显 | 高,每个连接占用独立进程/线程 |
| 并发处理能力 | 数万级(单进程处理数千连接) | 数千级(受进程/线程数限制) |
| 模块热加载 | 不支持(需 reload) | 支持(DSO 模块运行时加载) |
5.2 配置复杂度
| 维度 | Nginx | Apache |
|---|---|---|
| 配置文件风格 | 简洁、声明式、层级结构 | 类 XML 风格、指令繁多 |
| 目录级配置 | 不支持 .htaccess(仅限 server/location 块) | 支持 .htaccess,目录级动态覆盖 |
| 动态重写 | 仅支持 rewrite 指令(功能有限) | mod_rewrite 更强大灵活 |
| 学习曲线 | 中等(模型简洁但概念需理解) | 中等偏高(指令多、MPM 配置复杂) |
| 配置错误恢复 | 优雅(nginx -t 验证后 reload) | 可通过 .htaccess 局部修复 |
5.3 模块生态
| 维度 | Nginx | Apache |
|---|---|---|
| 模块加载 | 多数核心模块静态编译,动态模块需 --with-dynamic-modules | DSO 动态加载,灵活度高 |
| 语言集成 | 通过 FastCGI/Proxy 转发(如 php-fpm、uwsgi) | 直接嵌入(mod_php、mod_perl、mod_wsgi) |
| 第三方模块 | ngx_lua(OpenResty)、njs、众多商业模块 | 丰富但增长缓慢 |
| 负载均衡 | 原生支持(upstream),多种算法 | 通过 mod_proxy_balancer 实现,功能较弱 |
5.4 适用场景
| 场景 | 推荐方案 | 原因 |
|---|---|---|
| 静态资源 / CDN 边缘 | Nginx | 高性能静态文件服务,内存占用低 |
| 反向代理 / API 网关 | Nginx | 强大的 proxy_pass 和 upstream 生态 |
| 共享主机 / 多租户 | Apache | 支持 .htaccess,用户自主配置灵活 |
| PHP 应用(传统) | Apache + mod_php | 部署简单,无需额外进程管理 |
| PHP 应用(现代) | Nginx + php-fpm | 性能更好,资源配置灵活 |
| Python / Node.js 应用 | Nginx 反向代理 | 配合 WSGI/HTTP upstream,生态成熟 |
| 需要动态模块加载 | Apache | DSO 机制支持运行时加载/卸载模块 |
六、安全配置
6.1 隐藏版本号
Nginx:
server_tokens off;Apache:
ServerTokens Prod
ServerSignature Off6.2 限制请求方法
Nginx:
if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE)$) {
return 405;
}
# 或通过 map 更加高效:
map $request_method $bad_method {
default 0;
TRACE 1;
TRACK 1;
OPTIONS 1;
}
server {
if ($bad_method) {
return 405;
}
}Apache:
<LimitExcept GET POST HEAD PUT DELETE>
Require all denied
</LimitExcept>6.3 设置安全头
Nginx:
server {
# 点击劫持保护
add_header X-Frame-Options "SAMEORIGIN" always;
# XSS 过滤
add_header X-XSS-Protection "1; mode=block" always;
# MIME 类型嗅探防止
add_header X-Content-Type-Options "nosniff" always;
# 内容安全策略
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; frame-ancestors 'self';" always;
# 引用策略
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# 权限策略
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
}Apache:
<IfModule mod_headers.c>
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Content-Type-Options "nosniff"
Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
</IfModule>6.4 防 DDoS 基础配置
Nginx:
http {
# 限制连接速率
limit_req_zone $binary_remote_addr zone=ddos:10m rate=30r/s;
limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;
# 限制单个 IP 并发连接
limit_conn conn_per_ip 50;
# 限制请求体大小
client_body_buffer_size 1k;
client_max_body_size 1m;
# 限制请求头大小(防慢速攻击)
client_header_buffer_size 1k;
large_client_header_buffers 2 1k;
# 超时设置(防慢速连接)
client_body_timeout 10s;
client_header_timeout 10s;
keepalive_timeout 5s 5s;
send_timeout 10s;
server {
location / {
limit_req zone=ddos burst=20 nodelay;
proxy_pass http://backend;
}
# 针对特定路径关闭长连接
location /api/upload {
proxy_http_version 1.0;
proxy_set_header Connection "close";
}
}
}Apache:
# 启用 mod_reqtimeout 防慢速攻击
<IfModule mod_reqtimeout.c>
RequestReadTimeout header=10-20,MinRate=500
RequestReadTimeout body=10-20,MinRate=500
</IfModule>
# 启用 mod_evasive 防 DDoS
<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 5
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 10
DOSEmailNotify admin@example.com
</IfModule>
# 连接数限制
<IfModule mod_qos.c>
# 限制单个 IP 并发连接
QS_SrvMaxConnPerIP 50
# 限制请求速率
QS_SrvMaxConnRate 100
</IfModule>总结
- Nginx 适合作为反向代理、静态服务、负载均衡和微服务网关,尤其在高并发场景下优势明显。其事件驱动模型和简洁的配置语法使其成为现代云原生架构的首选。
- Apache 在 .htaccess 目录级配置、多租户共享主机和直接嵌入动态语言模块方面依然具有不可替代的生态优势。
- 现代架构中常用组合方案:Nginx 作反向代理前端 + Apache(或其他应用服务器)处理后端动态请求,兼顾性能与灵活性。
- 无论选择哪个服务器,安全加固(隐藏版本号、限制请求方法、设置安全头、防 DDoS)都是上线前的必备步骤。