利用nginx实现动静分离的负载均衡集群实战
以下是一个简化的实例,展示如何配置Nginx以实现动静分离和负载均衡。
# /etc/nginx/nginx.conf
user nginx;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include 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;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
# 动静分离
server {
listen 80;
server_name localhost;
# 静态文件
location ~* \.(jpg|jpeg|gif|png|css|js|ico|html)$ {
root /var/www/static;
expires 30d;
}
# 动态请求
location / {
proxy_pass http://dynamic_backend;
include /etc/nginx/proxy_params;
}
}
# 负载均衡配置
upstream dynamic_backend {
server backend1.example.com;
server backend2.example.com;
}
}
在这个配置中,我们定义了一个名为dynamic_backend
的upstream块,其中包含了两个后端服务器。然后在server块中,我们通过proxy\_pass指令把所有非静态文件的请求代理到这个upstream。静态文件则直接从/var/www/static
目录提供,并设置了30天的缓存过期时间。这样就实现了动静分离和负载均衡。
评论已关闭