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
| 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; keepalive 64; }
server { listen 80; location / { proxy_pass http://backend_servers; 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; } 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
| <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
|
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
<VirtualHost *:80> ServerName www.example.com 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 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 </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 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
| events { worker_connections 8192; use epoll; multi_accept on; }
http { 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_nopush on; tcp_nodelay on; sendfile on; proxy_buffer_size 8k; proxy_buffers 16 8k; proxy_busy_buffers_size 16k; 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
|
<IfModule mpm_event_module> ServerLimit 16 MaxRequestWorkers 4000 ThreadsPerChild 25 MinSpareThreads 75 MaxSpareThreads 250 ThreadLimit 64 ThreadsPerChild 25 </IfModule>
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
| upstream backend_servers { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; }
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
|
<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
| 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
| 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
| server { listen 8080; location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } }
|
7.2 Apache监控
1 2 3 4 5 6 7 8 9 10
| <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各有优势,选择取决于具体需求:
核心要点
- Nginx优势:高并发、低内存占用、配置简洁
- Apache优势:功能全面、模块丰富、.htaccess支持
- 混合架构:Nginx反向代理 + Apache处理动态内容
- 应用场景:根据需求灵活选择或组合使用
技术要点
- 反向代理配置:Nginx和Apache的实现方式
- 负载均衡:轮询、加权、最少连接等算法
- 高可用部署:Keepalived、集群配置
- 性能优化:并发优化、缓存策略
实践建议
- 高并发场景:选择Nginx
- 传统应用:选择Apache
- 混合架构:最佳实践
- 持续监控:性能指标和日志分析
- 定期优化:根据实际负载调整
可根据业务场景灵活选择或组合使用两种工具。