为实现Nginx与Tomcat的反向代理、动静分离和负载均衡,你需要做以下配置:
- 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 logs/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
# 动静分离
server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 8m;
client_body_buffer_size 128k;
proxy_connect_timeout 600;
proxy_read_timeout 600;
proxy_send_timeout 600;
proxy_buffer_size 16k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
# gzip 压缩
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css;
gzip_vary on;
# 静态文件处理
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
# 处理静态文件
location ~* \.(jpg|jpeg|gif|png|css|js|ico|html)$ {
access_log off;
log_not_found off;
expires 30d;
}
}
# 负载均衡配置
upstream tomcat_server {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
# 反向代理配置
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://tomcat_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
- 确保 Nginx 配置没有错误:
nginx -t
- 如果没有错误,重新加载 Nginx 配置:
nginx -s reload
在上述配置中,Nginx 作为反向代理接收来自客户端的请求,并将这些请求根据配置的负载均衡策略分发到在 \`upstrea