Nginx 处理 HTTP 请求的过程可以分为多个阶段,以下是一个详细的流程说明:
GET /index.html HTTP/1.1)和请求头(如 Host, User-Agent)。Host 用于虚拟主机匹配)。Host 字段匹配对应的 server 块(虚拟主机配置)。server 块,使用默认的 server(通常是第一个定义的或标记为 default_server 的)。root 或 alias 指令将 URL 路径映射到文件系统路径。try_files 指令可自定义回退逻辑)。proxy_pass 转发到后端(如 FastCGI、uWSGI、Node.js 等)。rewrite 重写 URL。allow/deny 基于 IP 的访问限制。limit_req 限制请求速率。auth_basic 或 JWT 验证。add_header 设置跨域头。sendfile 零拷贝优化。proxy_cache,可能直接返回缓存内容。access_log)和错误日志(error_log)。log_format 自定义。server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://backend:3000;
proxy_set_header Host $host;
}
location ~* \.(jpg|png)$ {
expires 30d; # 缓存控制
}
}
nginx
sendfile on;nginx
gzip on;nginx
keepalive_timeout 65;nginx
location ~* \.(js|css)$ {
expires 1y;
}root/alias 路径和文件权限。allow/deny 规则或防火墙。如果需要更具体的场景分析,可以提供你的配置或需求细节!