Nginx 配置反向代理的技巧有很多,以下是一些常用的技巧:
选择合适的负载均衡算法:Nginx 支持多种负载均衡算法,如轮询(round-robin)、加权轮询(weighted round-robin)、最少连接(least_conn)和 IP 哈希(ip_hash)。根据实际需求选择合适的算法。
设置超时时间:为了防止慢客户端或后端服务器影响整体性能,可以设置代理超时时间。例如:
proxy_connect_timeout 75s;
proxy_send_timeout 75s;
proxy_read_timeout 75s;
proxy_http_version 1.1;
proxy_set_header Connection "";
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public";
}
sub_filter 'ad_code' 'replacement_text';
sub_filter_once off;
gzip_static on;
location ~ /purge(/.*) {
allow 127.0.0.1;
deny all;
proxy_cache_purge cache_name $scheme$proxy_host$request_uri;
}
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;
limit_req zone=mylimit burst=5;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
根据实际需求,可以灵活运用这些技巧来优化 Nginx 反向代理的性能和安全性。