如何在 Nginx 后面使用 Phoenix 设置 Websockets?

pau*_*l h 2 nginx elixir websocket phoenix-framework phoenix-channels

我正在尝试设置网络套接字以通过 Nginx 访问 Phoenix 应用程序,但不断收到 403 错误。任何人都可以建议正确的配置以使其在生产中工作 - 开发环境很好。

我的 Nginx 配置:

upstream phoenix {
  server 127.0.0.1:4000 max_fails=5 fail_timeout=60s;
}

server {
  server_name <app-domain>;
  listen 80;

  location / {
    allow all;

    # Proxy Headers
    proxy_http_version 1.1;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-Cluster-Client-Ip $remote_addr;

    # The Important Websocket Bits!
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    proxy_pass http://phoenix;
  }
}
Run Code Online (Sandbox Code Playgroud)

我的 prod.exs conf:

use Mix.Config

config :logger, level: :info
config :phoenix, :serve_endpoints, true

config :app, App.Endpoint,
  http: [port: 4000],
  url: [host: "127.0.0.1", port: 4000],
  root: '.',
  cache_static_manifest: "priv/static/manifest.json",
  server: true

config :app, App.Repo,
  username: System.get_env("MONGO_USERNAME"),
  password: System.get_env("MONGO_PASSWORD"),
  database: "template",
  hostname: "localhost",
  pool_size: 10
Run Code Online (Sandbox Code Playgroud)

如有必要,我可以根据要求提供任何其他信息。

该应用程序可以通过域名正常访问,最后一个也是唯一剩下的问题是让网络套接字工作。

非常感谢任何能指出我正确方向的人。

The*_*Anh 5

我按照凤凰网站的指南进行操作。 Exrm 发布 - Phoenix

你的 nginx.config 缺少这个:

# The following map statement is required
# if you plan to support channels. See https://www.nginx.com/blog/websocket-nginx/
map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}
Run Code Online (Sandbox Code Playgroud)

将版本发送到我的服务器后,在本地机器上生成版本时,我也遇到了一些错误。

所以我建议你应该在你的服务器环境中生成你的版本。

编辑:

浏览器控制台中的错误:

ws://phoenix.hollyer.me.uk/socket/websocket?token=&vsn=1.0.0' failed: Error during WebSocket handshake: Unexpected response code: 403

这可能是这个错误。你应该尝试在你的服务器中启动你的控制台:

[error] Could not check origin for Phoenix.Socket transport.

This happens when you are attempting a socket connection to
a different host than the one configured in your config/
files. For example, in development the host is configured
to "localhost" but you may be trying to access it from
"127.0.0.1". To fix this issue, you may either:

  1. update [url: [host: ...]] to your actual host in the
     config file for your current environment (recommended)

  2. pass the :check_origin option when configuring your
     endpoint or when configuring the transport in your
     UserSocket module, explicitly outlining which origins
     are allowed:

        check_origin: ["https://example.com",
                        "//another.com:888", "//other.com"]
Run Code Online (Sandbox Code Playgroud)

所以你可以像这样重新配置你的主机:

[url: [host: "http://www.phoenix.hollyer.me.uk"]]
Run Code Online (Sandbox Code Playgroud)

将 :check_origin 选项传递给您的端点配置或 UserSocket 模块:

check_origin: ["http://www.phoenix.hollyer.me.uk"]
Run Code Online (Sandbox Code Playgroud)

然后再次尝试部署。希望对您有所帮助!