[英]NGinx forward websocket from 80 to websocket port
I am using Nginx as a web host and proxy for a websocket running on the same device listening on port 8888. Trying to find a way to have nginx listen on 80 and forward the websocket requests to the internal port. 我使用Nginx作为web主机和代理在同一设备上运行的websocket,监听端口8888.试图找到一种方法让nginx监听80并将websocket请求转发到内部端口。 Without exposing a new port to the outside. 不将新端口暴露在外面。 Is this even possible? 这甚至可能吗?
UPDATE: 更新:
This is my current configuration: 这是我目前的配置:
error_log /var/log/nginx/error_log.log warn;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream websocket {
server localhost:8888;
}
server {
listen 80;
#listen [::]:80 default_server;
# SSL configuration
#
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /var/www/html/EncoderAdmin;
# Add index.php to the list if you are using PHP
index index.php index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location /ws {
proxy_pass http://localhost:8888;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
When I try to connect to it with ws://[address]/ws I get: 当我尝试使用ws:// [address] / ws连接到它时,我得到:
WebSocket connection to 'ws://[address]/ws' failed: Error during WebSocket handshake: Unexpected response code: 400 与'ws:// [地址] / ws'的WebSocket连接失败:WebSocket握手期间出错:意外响应代码:400
Yes, it's possible assuming you can distinguish the normal HTTP requests and the socket ones. 是的,可以假设您可以区分正常的HTTP请求和套接字请求。
The simplest solution is to match the socket uri with location
, for example all the requests to /ws
will be redirected to localhost:8888
, any other url to localhost:8889
. 最简单的解决方案是将套接字uri与location
匹配,例如,对/ws
所有请求将被重定向到localhost:8888
,任何其他URL到localhost:8889
。 Here it is an example of configuration 这是配置的一个例子
server {
server_name _;
location /ws {
proxy_pass http://localhost:8888;
# this magic is needed for WebSocket
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
location / {
proxy_pass http://localhost:8889;
}
}
You should also remember to bind the websocket server to localhost:8888 and not to 0.0.0.0:8888. 您还应该记得将websocket服务器绑定到localhost:8888而不是0.0.0.0:8888。 This step is not needed but with it the original port is not exposed! 不需要此步骤,但使用它原始端口不会暴露!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.