作为一款高性能的HTTP代理服务器,Nginx在安全性和性能方面的配置至关重要。以下是一套全面的优化方案:
server_tokens off;
more_clear_headers Server;
more_clear_headers X-Powered-By;
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
if ($server_protocol !~* "HTTP/1.1|HTTP/2.0") {
return 444;
}
location /admin/ {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
location / {
limit_req zone=req_limit burst=20 nodelay;
}
}
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy "default-src 'self'";
add_header Referrer-Policy "no-referrer-when-downgrade";
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
ssl_ecdh_curve secp384r1;
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 24k;
proxy_max_temp_file_size 0;
proxy_http_version 1.1;
proxy_set_header Connection "";
keepalive_timeout 75s;
keepalive_requests 100;
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
}
}
location ~* \.(bak|conf|sh|sql|ini)$ {
deny all;
return 404;
}
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
limit_conn conn_limit 20;
client_body_timeout 10s;
client_header_timeout 10s;
send_timeout 10s;
}
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$upstream_cache_status';
access_log /var/log/nginx/security.log security;
nginx -t
测试配置语法通过以上配置,您的Nginx HTTP代理将在安全性和性能方面得到显著提升,同时保持对现代Web应用的兼容性。