You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Laravel Octane官方文档的Nginx配置用close而非keepalive?

关于Laravel Octane Nginx配置使用connection close而非keepalive的疑问

我发现Laravel Octane官方文档中,在将请求反向代理至Octane监听端口时,Nginx配置设置了connection close而非keepalive,特此请教各位原因。相关配置如下:

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}
 
server {
    listen 80;
    listen [::]:80;
    server_name domain.com;
    server_tokens off;
    root /home/forge/domain.com/public;
 
    index index.php;
 
    charset utf-8;
 
    location /index.php {
        try_files /not_exists @octane;
    }
 
    location / {
        try_files $uri $uri/ @octane;
    }
 
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }
 
    access_log off;
    error_log  /var/log/nginx/domain.com-error.log error;
 
    error_page 404 /index.php;
 
    location @octane {
        set $suffix "";
 
        if ($uri = /index.php) {
            set $suffix ?$query_string;
        }
 
        proxy_http_version 1.1;
        proxy_set_header Host $http_host;
        proxy_set_header Scheme $scheme;
        proxy_set_header SERVER_PORT $server_port;
        proxy_set_header REMOTE_ADDR $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
 
        proxy_pass http://127.0.0.1:8000$suffix;
    }
}
原因解析
  • 为了兼容WebSocket场景:Octane支持WebSocket(比如配合Laravel Echo使用),这里的map指令就是用来处理WebSocket的升级请求。当客户端发起WebSocket连接时,Upgrade请求头存在,此时$connection_upgrade会返回upgrade,保持连接持久化;而普通HTTP请求没有Upgrade头,所以设置Connection: close——这是因为Octane基于Swoole/OpenSwoole或RoadRunner运行,本身会管理连接池,不需要Nginx来维持keepalive,避免两种连接管理机制冲突。

  • Octane自身的连接管理逻辑:Octane运行在常驻进程服务器上,它会自己维护连接池、复用连接来提升性能。如果Nginx强制开启keepalive,反而可能导致Nginx和Octane之间的连接闲置,甚至出现连接数耗尽的情况——毕竟Octane的进程长期运行,连接处理逻辑和传统FPM完全不同,不需要依赖Nginx的keepalive来复用连接。

  • 避免长连接浪费资源:对于普通HTTP请求,设置Connection: close能让Nginx在请求完成后主动关闭和Octane的连接,避免不必要的长连接占用服务器资源。Octane本身可以高效处理新请求,完全不需要依赖Nginx的keepalive机制。

  • 官方配置的兼容性考量:这个配置是官方经过多场景测试的通用方案,既兼顾了WebSocket和普通HTTP请求,又能确保在各种环境下稳定运行,不会因为keepalive设置导致连接超时、进程阻塞等奇怪问题。

内容的提问来源于stack exchange,提问作者Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:52:38