Web服务器对比架构实战:Nginx与Apache反向代理、负载均衡完整配置方案

一、Nginx与Apache概述

1.1 核心特性对比

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Nginx vs Apache:
架构模式:
Nginx: 事件驱动、异步非阻塞
Apache: 多进程/多线程、同步阻塞

性能:
Nginx: 高并发性能优秀
Apache: 功能全面,性能中等

配置:
Nginx: 配置简洁
Apache: .htaccess动态配置

模块:
Nginx: 编译时模块
Apache: 运行时模块

适用场景:
Nginx: 静态文件、反向代理、负载均衡
Apache: 动态内容、.htaccess需求

1.2 选型建议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
选择Nginx如果:
1. 高并发场景(>10000并发)
2. 反向代理需求
3. 负载均衡需求
4. 资源有限
5. 简单配置

选择Apache如果:
1. 需要.htaccess动态配置
2. 丰富的模块生态
3. 传统应用兼容
4. 复杂URL重写
5. 企业级功能需求

混合架构:
- 前端用Nginx做反向代理
- 后端用Apache处理动态内容

二、Nginx反向代理

2.1 Nginx反向代理基础

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# /etc/nginx/sites-available/reverse-proxy
server {
listen 80;
server_name www.example.com;

location / {
proxy_pass http://backend_servers;

# 基础代理头
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 10s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

# 缓冲设置
proxy_buffering on;
proxy_buffer_size 8k;
proxy_buffers 16 8k;
proxy_busy_buffers_size 16k;
}
}

# 定义后端服务器组
upstream backend_servers {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

2.2 Nginx负载均衡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 负载均衡配置
upstream backend_servers {
# 基础轮询
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;

# 加权轮询
# server 192.168.1.10:8080 weight=3;
# server 192.168.1.11:8080 weight=2;
# server 192.168.1.12:8080 weight=1;

# 最少连接
# least_conn;

# IP哈希
# ip_hash;

# 健康检查
keepalive 64;
}

server {
listen 80;
location / {
proxy_pass http://backend_servers;

# HTTP/1.1优化
proxy_http_version 1.1;
proxy_set_header Connection "";

# 其他配置...
}
}

2.3 Nginx高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 完整反向代理配置
upstream app_backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 backup;

keepalive 32;
}

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

# 访问日志
access_log /var/log/nginx/api_access.log main;
error_log /var/log/nginx/api_error.log warn;

# 限流
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req zone=api_limit burst=20 nodelay;

location / {
proxy_pass http://app_backend;

# 请求头
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_set_header Connection "";

# 超时
proxy_connect_timeout 10s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;

# 缓冲
proxy_buffering on;
proxy_buffer_size 8k;
proxy_buffers 16 8k;

# 错误处理
proxy_intercept_errors on;
error_page 502 503 504 /50x.html;
}

# WebSocket支持
location /ws {
proxy_pass http://app_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 3600s;
}

# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
proxy_pass http://app_backend;
proxy_cache my_cache;
proxy_cache_valid 200 1d;
add_header Cache-Control "public, max-age=86400";
}
}

三、Apache反向代理

3.1 Apache mod_proxy配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# /etc/apache2/sites-available/reverse-proxy.conf
<VirtualHost *:80>
ServerName www.example.com

# 启用代理模块
ProxyPass / http://192.168.1.10:8080/
ProxyPassReverse / http://192.168.1.10:8080/

# 请求头
ProxyPreserveHost On

# 日志
LogLevel proxy:warn
ErrorLog ${APACHE_LOG_DIR}/proxy_error.log
CustomLog ${APACHE_LOG_DIR}/proxy_access.log combined

# 超时
ProxyTimeout 60
</VirtualHost>

3.2 Apache负载均衡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Apache负载均衡配置
# 启用模块
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so

<VirtualHost *:80>
ServerName www.example.com

# 定义worker
ProxyPass / balancer://mycluster/
ProxyPassReverse / balancer://mycluster/

<Proxy balancer://mycluster>
BalancerMember http://192.168.1.10:8080 loadfactor=3
BalancerMember http://192.168.1.11:8080 loadfactor=3
BalancerMember http://192.168.1.12:8080 loadfactor=2
BalancerMember http://192.168.1.13:8080 status=+H

# 负载均衡算法
ProxySet lbmethod=byrequests # 请求数
# ProxySet lbmethod=bytraffic # 流量
# ProxySet lbmethod=bybusyness # 负载

# 会话粘性
ProxySet stickysession=JSESSIONID
</Proxy>

# 监控接口
ProxyPass /balancer-manager !
ProxyStatus On
<Location /balancer-manager>
SetHandler balancer-manager
Require all granted
</Location>
</VirtualHost>

3.3 Apache高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<VirtualHost *:80>
ServerName api.example.com

# 限流
<Directory />
Require all granted
</Directory>

# 负载均衡配置
<Proxy balancer://app_cluster>
# 服务器列表
BalancerMember http://192.168.1.10:8080 max=100 retry=30 timeout=20
BalancerMember http://192.168.1.11:8080 max=100 retry=30 timeout=20
BalancerMember http://192.168.1.12:8080 max=100 retry=30 timeout=20

# 算法
ProxySet lbmethod=byrequests

# 健康检查
# mod_proxy_http需要配合使用
</Proxy>

# 反向代理
ProxyPass / balancer://app_cluster/
ProxyPassReverse / balancer://app_cluster/

# 请求头
ProxyAddHeaders On
ProxyPreserveHost On
RequestHeader set X-Forwarded-Proto "http"
RequestHeader set X-Forwarded-Port "80"

# 超时
ProxyTimeout 60

# WebSocket支持
RewriteEngine on
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteCond %{HTTP:Connection} upgrade [NC]
RewriteRule ^/ws/(.*) ws://192.168.1.10:8080/ws/$1 [P,L]

# 日志
LogLevel proxy:warn
ErrorLog ${APACHE_LOG_DIR}/api_error.log
CustomLog ${APACHE_LOG_DIR}/api_access.log combined
</VirtualHost>

四、性能优化对比

4.1 Nginx优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Nginx性能优化
events {
worker_connections 8192;
use epoll;
multi_accept on;
}

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

# 文件句柄缓存
open_file_cache max=10000 inactive=300s;
open_file_cache_valid 300s;
open_file_cache_min_uses 2;

# TCP优化
tcp_nopush on;
tcp_nodelay on;
sendfile on;

# 代理优化
proxy_buffer_size 8k;
proxy_buffers 16 8k;
proxy_busy_buffers_size 16k;

# keepalive
keepalive_timeout 65;
keepalive_requests 1000;
}

4.2 Apache优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Apache性能优化(/etc/apache2/apache2.conf)

# MPM配置(使用event模式)
<IfModule mpm_event_module>
ServerLimit 16
MaxRequestWorkers 4000
ThreadsPerChild 25
MinSpareThreads 75
MaxSpareThreads 250
ThreadLimit 64
ThreadsPerChild 25
</IfModule>

# KeepAlive配置
KeepAlive On
MaxKeepAliveRequests 1000
KeepAliveTimeout 5

# 压缩
LoadModule deflate_module modules/mod_deflate.so
<Location />
SetOutputFilter DEFLATE
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI \
\.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
</Location>

五、高可用部署

5.1 Nginx高可用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 主Nginx配置
upstream backend_servers {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

# Keepalived配置
# /etc/keepalived/keepalived.conf
global_defs {
router_id nginx-master
}

vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -5
fall 3
rise 2
}

vrrp_instance VI_NGINX {
state MASTER
interface eth0
virtual_router_id 100
priority 100
advert_int 1

authentication {
auth_type PASS
auth_pass password123
}

virtual_ipaddress {
192.168.1.100
}

track_script {
chk_nginx
}
}

5.2 Apache高可用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Apache集群配置
# 使用mod_proxy_balancer进行负载均衡
# 配合Keepalived实现高可用

# 监控配置
<Location /server-status>
SetHandler server-status
Require local
</Location>

<Location /server-info>
SetHandler server-info
Require local
</Location>

六、实战案例

6.1 微服务架构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Nginx微服务网关
upstream user_service {
server 192.168.1.100:8080;
server 192.168.1.101:8080;
}

upstream order_service {
server 192.168.1.102:8081;
server 192.168.1.103:8081;
}

upstream payment_service {
server 192.168.1.104:8082;
server 192.168.1.105:8082;
}

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

# 用户服务
location /api/user/ {
proxy_pass http://user_service;
proxy_set_header Host $host;
}

# 订单服务
location /api/order/ {
proxy_pass http://order_service;
proxy_set_header Host $host;
}

# 支付服务
location /api/payment/ {
proxy_pass http://payment_service;
proxy_set_header Host $host;
}
}

6.2 容器化部署

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Nginx + Docker Compose
version: '3.8'

services:
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./sites:/etc/nginx/sites-enabled
depends_on:
- app1
- app2

app1:
image: myapp:latest
expose:
- "8080"

app2:
image: myapp:latest
expose:
- "8080"

七、监控和日志

7.1 Nginx监控

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Nginx状态监控
server {
listen 8080;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}

# 访问: http://localhost:8080/nginx_status
# 输出:
# Active connections: 10
# server accepts handled requests
# 1000 1000 5000
# Reading: 0 Writing: 5 Waiting: 5

7.2 Apache监控

1
2
3
4
5
6
7
8
9
10
# Apache状态页面
<Location /server-status>
SetHandler server-status
<RequireAny>
Require ip 127.0.0.1
Require ip 192.168.1.0/24
</RequireAny>
</Location>

ExtendedStatus On

八、最佳实践

8.1 安全配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Web服务器安全最佳实践:
Nginx:
- 隐藏版本号: server_tokens off
- 限制请求大小: client_max_body_size 10m
- 禁用不必要的服务器名称

Apache:
- ServerTokens Prod
- ServerSignature Off
- 禁用.htaccess
- 限制请求体大小: LimitRequestBody

通用:
- HTTPS强制
- 安全头部
- 限流防护
- 定期更新

8.2 性能优化

1
2
3
4
5
6
7
8
9
10
11
12
13
性能优化建议:
Nginx:
- 使用最新稳定版本
- Worker进程数设为CPU核数
- 启用Gzip压缩
- 使用HTTP/2
- 静态文件缓存

Apache:
- 选择合适的MPM
- 启用KeepAlive
- 使用mod_deflate压缩
- 优化线程数量

九、总结

Nginx和Apache各有优势,选择取决于具体需求:

核心要点

  1. Nginx优势:高并发、低内存占用、配置简洁
  2. Apache优势:功能全面、模块丰富、.htaccess支持
  3. 混合架构:Nginx反向代理 + Apache处理动态内容
  4. 应用场景:根据需求灵活选择或组合使用

技术要点

  • 反向代理配置:Nginx和Apache的实现方式
  • 负载均衡:轮询、加权、最少连接等算法
  • 高可用部署:Keepalived、集群配置
  • 性能优化:并发优化、缓存策略

实践建议

  1. 高并发场景:选择Nginx
  2. 传统应用:选择Apache
  3. 混合架构:最佳实践
  4. 持续监控:性能指标和日志分析
  5. 定期优化:根据实际负载调整

可根据业务场景灵活选择或组合使用两种工具。