要配置NGINX代理Websocket,您需要確保NGINX可以正確處理Websocket協議及其升級請求。這是有關如何設置的分步指南:
/etc/nginx/nginx.conf
或/etc/nginx/sites-available/
etcement configurations)。添加Websocket代理設置:
在您要啟用Websocket支持的http
或server
塊中,添加以下配置摘要:
<code class="nginx">http { ... server { listen 80; server_name example.com; location / { proxy_pass http://your_backend_server; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } }</code>
proxy_http_version 1.1
確保nginx使用http/1.1,這是WebSocket連接所需的。proxy_set_header Upgrade $http_upgrade
和proxy_set_header Connection "upgrade"
對於處理Websocket升級請求至關重要。proxy_cache_bypass $http_upgrade
確保Websocket Connections Bypass Caching通常合適。nginx -t
測試語法錯誤的配置,然後重新加載或使用sudo systemctl reload nginx
或sudo systemctl restart nginx
。為了確保NGINX正確處理Websocket連接,在您的NGINX配置中的location
塊中需要以下設置:
proxy_pass
:指定將代理Websocket請求的後端服務器。proxy_http_version 1.1
:將HTTP協議版本設置為1.1,這是WebSocket Connections所需的。proxy_set_header Upgrade $http_upgrade
:將Upgrade
標頭的值從客戶端傳遞到後端服務器。proxy_set_header Connection "upgrade"
:將Connection
標頭設置為“升級”,向Websocket升級請求發出信號。proxy_set_header Host $host
:將主機標頭從客戶端傳遞到後端服務器。proxy_cache_bypass $http_upgrade
:確保Websocket Connections旁路緩存,因為不應緩存WebSocket連接。這些設置共同努力,以確保正確處理並轉發到後端服務器。
為了確保正確處理WebSocket協議升級,必須按照上一節中所述實現必要的配置。以下是其他提示,可以驗證升級是否正確處理:
proxy_set_header Upgrade $http_upgrade
和proxy_set_header Connection "upgrade"
。/var/log/nginx/
中找到。成功的Websocket升級不會記錄錯誤。wscat
或websocat
手動啟動WebSocket連接,並驗證它們是否成功地通過NGINX連接。通過遵循以下步驟,您可以確保NGINX正確處理WebSocket協議升級。
如果您在NGINX中遇到websocket的問題,請按照以下故障排除步驟:
http
, server
和location
塊中。使用nginx -t
測試語法錯誤的配置。/var/log/nginx/
)是否有任何與Websoket相關的錯誤或問題。查找與WebSocket連接和升級請求有關的條目。wscat
或websocat
等工具直接從命令行測試Websocket連接。這可以幫助隔離NGINX還是後端服務器的問題。proxy_read_timeout
和proxy_send_timeout
。通過系統地瀏覽這些故障排除步驟,您應該能夠識別和解決NGINX中Websocket的問題。
以上是如何為Websocket配置NGINX?的詳細內容。更多資訊請關注PHP中文網其他相關文章!