以下是14个Nginx的核心功能点及简要解析,建议IT工程师和运维人员收藏备用:
proxy_pass
指令快速配置代理location / {
proxy_pass http://backend_servers;
}
upstream backend {
server 10.0.0.1 weight=3;
server 10.0.0.2;
server 10.0.0.3 backup; # 备用服务器
}
location /static/ {
root /data/www;
expires 30d; # 缓存控制
}
server {
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
}
rewrite
规则(支持正则)rewrite ^/old-url/(.*)$ /new-url/$1 permanent;
location /admin/ {
deny 192.168.1.100;
allow 10.0.0.0/24;
deny all;
}
gzip on;
gzip_types text/plain application/json;
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=mycache:10m;
location / {
proxy_cache mycache;
proxy_cache_valid 200 1h;
}
log_format main '$remote_addr - $request_time';
access_log /var/log/nginx/access.log main;
location /ws/ {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
location /api/ {
limit_req zone=mylimit burst=20;
}
location ~* \.(jpg|css|js)$ {
root /data/static;
}
location /api/ {
proxy_pass http://app_server;
}
ngx_http_rewrite_module
、ngx_stream_core_module
等worker_processes
、worker_connections
等参数server_tokens
、禁用不必要HTTP方法收藏提示:根据实际场景组合使用这些功能,可通过nginx -T
验证配置完整性。遇到问题时,检查错误日志/var/log/nginx/error.log
快速定位问题。