Failed error during websocket handshake unexpected response code 301

I have already looked into the answer to RoR 5.0.0 ActionCable wss WebSocket handshake: Unexpected response code: 301 but it was not applicable to my case. I use an nginx-proxy as a front for sev...

I have already looked into the answer to RoR 5.0.0 ActionCable wss WebSocket handshake: Unexpected response code: 301 but it was not applicable to my case.

I use an nginx-proxy as a front for several web-servers running in docker-containers. I use the nginx-config-template from https://github.com/jwilder/nginx-proxy

Now in my docker-container I have another nginx with the following config:

map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}

upstream websocket {
    server my-websocket-docker-container:8080;
}

server {
    root /src/html;


    location /websocket/ {
        resolver 127.0.0.11 ipv6=off;
        proxy_pass http://websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }

    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;
    }

    ...

}

When trying to connect to wss://example.com/websocket I get the aforementioned error about unexpected response code 301. When I curl the websocket-url manually I can see the nginx response telling me «301 moved permanantly». But why? Where is this coming from?

Can anybody help? Thanks!

asked Aug 11, 2018 at 17:54

Tobias Gassmann's user avatar

Tobias GassmannTobias Gassmann

11k13 gold badges57 silver badges89 bronze badges

5

I was facing a similar issue today. I was using the «classic» WebSocket API and NGINX to test the connection between some services. I came up with the following solution:

WebSocket instance creation:

const websocket = new WebSocket('ws://' + window.location.host + '/path');

Nginx config:

location /path {
    proxy_pass http://websocket:port;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

Where:

  1. path is the path to be redirected
  2. websocket is the hostname or the IP of the host
  3. port is the port where the application is served on the host

answered Jan 12, 2021 at 13:27

LoolKovsky's user avatar

1

Содержание

  1. getting 301 redirect on ssl connection while on http things work fine. #333
  2. Comments
  3. Footer
  4. RoR 5.0.0 ActionCable wss WebSocket handshake: Unexpected response code: 301
  5. 3 Answers 3
  6. WebSocket connection fails with 301 while using Go on AWS Application Load Balancer
  7. WebSocket handshake: Unexpected response code: 301 #15
  8. Comments
  9. Footer
  10. Error during WebSocket handshake
  11. Silent2000
  12. Silent2000
  13. Silent2000
  14. Silent2000
  15. Silent2000
  16. Silent2000
  17. Attachments
  18. Silent2000

getting 301 redirect on ssl connection while on http things work fine. #333

Hi, Im getting a 301 error when on https.
‘wss://example-site.com/websocket’ failed: Error during WebSocket handshake: Unexpected response code: 301

Here is my nginx configuration

any ideas as to why ? I had successfully configured this with http but this doesnt work on https.
Any ideas or anyone encountered this anytime ?

The text was updated successfully, but these errors were encountered:

Did you succeed with that? I have same problem.

No, Not yet. I wonder no one replied here yet 🙂

The issue is most likely rewrite /websocket/(.*) /$1 break; try removing that.

You could also try: proxy_redirect off; inside the location /websocket <> block.

@moaa I have already tried that out but I still get the same error.

@pamio do you have force_ssl enabled in your rails configuration?

Yes Its enabled. Should that not be ?

I tried to comment that out but no change @moaa 🙁

@pamio did you restart everything after making the change? Including all of your standalone servers?

force_ssl = true (http://api.rubyonrails.org/classes/ActionController/ForceSSL/ClassMethods.html) will issue a redirect for any non ssl request to the secured url. According to your nginx config, you are using proxy_pass to «http» . Since the standalone server is really just your app running under Thin, I’m assuming this is where your redirect is coming from.

Hi @moaa, Yes I did restart everything including standalone servers but no luck.

Hi @moaa, I go this working by removing force_ssl=true , I also had to use hiredis as redis driver as I was getting no event machine initialized error and things started working. Thanks for your help and pointing me to the right direction. Cheers!

@Maxyss, Let me know if you are still facing this issue. May be I can help you with this.

@pamio, thank you. Solved my problem.
In production.rb I set force_ssl=false and in application_controller.rb I set force_ssl if: «Rails.env.production? && action_name != ‘dialog_chat’»

@kesha-antonov — How do we get the action_name for /cable?

@ACPK if still of interest, you can check against request.path in force_ssl :if , e.g.

if anyone come here looking for answer, I think best to do it is you set it in environment file
production.rb

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

RoR 5.0.0 ActionCable wss WebSocket handshake: Unexpected response code: 301

Hello I’m trying to serve a simple chat using ror 5.0.0 beta (with puma) working on production mode (in localhost there are no problems).

This is my Nginx configuration:

This is config/redis/cable.yml

production: url: redis://localhost:6379/1

development: url: redis://localhost:6379/2

test: url: redis://localhost:6379/3

and config/environments/production.rb

And this is the error i’m receiving:

application-[. ].js:27 WebSocket connection to ‘wss://mydomain/cable’ failed: Error during WebSocket handshake: Unexpected response code: 301

Any tips? 🙂 Thanks

3 Answers 3

I solved adding phusion passenger.

nginx config is now :

You have to remove default folder config/redis/cable.yml and move that file to /config only.

For SSL just enable default ssl options and it will works .-)

Thanks everyone for the help

Your websocket URI is /cable/ and not /cable , so the latter will hit the location / block. Try:

Also, not sure you need a break; in there. I presume the missing > between the two location blocks is just a typo in the question.

EDIT1: Added rewrite to restore correct upstream mapping.

EDIT2: Alternative solution is to explicitly rewrite /cable to /cable/ like this:

I spend almost 5 hours yesterday trying to solve this particular problem. I ended up using a separate domain for the websocket connection called ws.example.com as everything else resulted in a 301 redirect .

Here’s is my nginx.conf file. I’ve removed the SSL parts, but you could just insert your own. Note that you need nginx 1.4+ as everything prior to this version doesn’t support websocket proxying.

I read somewhere that allowed_request_origins didn’t work as expected so I went the safe way (until the bug is fixed) and turned the checker of completely using ActionCable.server.config.disable_request_forgery_protection = true .

Here’s my cable.ru file for starting action cable.

I’m also using the latest rails version from Github.

Источник

WebSocket connection fails with 301 while using Go on AWS Application Load Balancer

Part of AWS Collective

I’m trying to run a Go Server with WebSockets on an AWS Application Load Balancer but I am getting an ‘Error during WebSocket handshake: Unexpected response code: 301’.

AWS says that The Application Load Balancers supports WebSockets via ws:// protocols but I can not find any further documentation other than the following:

The Application Load Balancer supports two additional protocols: WebSocket and HTTP/2.

WebSocket allows you to set up long-standing TCP connections between your client and your server. This is a more efficient alternative to the old-school method which involved HTTP connections that were held open with a “heartbeat” for very long periods of time. WebSocket is great for mobile devices and can be used to deliver stock quotes, sports scores, and other dynamic data while minimizing power consumption. ALB provides native support for WebSocket via the ws:// and wss:// protocols.

I can get JavaScript to connect to my Go server via WebSockets locally but when I deploy AWS it does not work. This is when the JavaScript displays a 301 error.

The Application Load Balancer is listening on HTTP: 80 and that traffic is being directed to HTTPS: 443. All of the Security Groups are pretty much similarly set up to allow traffic through. If I do a normal GET call to retrieve data from my server while deployed on AWS it works perfectly fine.

Local call that works to connect to localhost

Connect to remote server that does not work.

I expect to be able to establish a WebSocket connection but the following error is returning from the JavaScript file:

Источник

WebSocket handshake: Unexpected response code: 301 #15

I was working few days ago with the Microphone and it was working well.
Today I have an erreur when I do mic.connect(clientToken), I have this message :

WebSocket connection to ‘wss://api.wit.ai/speech_ws’ failed: Error during WebSocket handshake: Unexpected response code: 301

My web page is in local with an https and the host is registred in the wit admin console.
I have reset the tocken but the problem persist.

The text was updated successfully, but these errors were encountered:

I have got the same issue here too. According to the article below It seems that the HTTP error 301 indicates that the server has been moved to another URL but I still wonder how to solve the issue. http://www.checkupdown.com/status/E301.html

Hi, we are in the process of moving to a new infra (see https://wit.ai/blog/2017/02/10/wit-community-update).
This new infra cannot accept websocket connections on api.wit.ai, so we created ws.wit.ai and started redirecting (301) to this new domain.

Unfortunately, we did not expect the fact that ws (the JS library for websocket that we use) does not follow redirects and instead throws an error (more at websockets/ws#812)

We’ll publish a new version of microphone.js today to use ws.wit.ai instead of api.wit.ai as a domain name.
In the meantime, you can use localStorage.setItem(‘wit_ws’, ‘wss://ws.wit.ai/speech_ws’) to override the default host.

Sorry for the inconvenience and thank you for your patience.

Thanks, it is working now!

Nice, you guys should update the docs as well.

@JoabMendes which docs are you referring to?

@blandinw The quickstart.md has the 0.7 version on the step 1, not the latest one.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Error during WebSocket handshake

Silent2000

New Member

Administrator

WCS сервер по-умолчанию слушает порт 8080 для websocket и порт 8443 для websocket ssl
Пример:

Silent2000

New Member

Administrator

Administrator

Silent2000

New Member

Silent2000

New Member

Administrator

Administrator

Silent2000

New Member

Silent2000

New Member

Administrator

Доступ demo/demo открыт только в том случае, когда сервер запущен с флагом -DstartWithDemoUser=true, как показано выше.

Апач сервер здесь совсем не используется.

1. Убедитесь что WCS сервер запущен. Вы должны видеть два Linux-процесса

Должны быть порты:
8888 — https dashboard
9091 — http dashboard
8443 — websocket https
8080 — websocket

3. Пройдите по этим портам telnet-ом и убедитесь что они открыты.
Пример:

4. Откройте Dashboard чтобы протестировать Two Way Streaming, нажмите Connect чтобы убедиться, что соединение устанавливается и переходит в ESTABLISHED
Для https
https://host:8888
wss://host:8443
Для http
http://host:9091
ws://host:8080

5. Если вы используете https и wss в браузере Google Chrome и еще не установили SSL сертификат, откройте предварительно страницу https://host:8443 чтобы разрешить браузеру использовать самоподписный сертификат, который отдает сервер по-умолчанию. Скриншоты здесь: https://flashphoner.com/docs/wcs5/w. ide-2/index.html?quick_start_installation.htm

В итоге, вы должны получить ESTABLISHED. Это значит что соединение с сервером установлено и можно двигаться дальше.

Attachments

Silent2000

New Member

Доступ demo/demo открыт только в том случае, когда сервер запущен с флагом -DstartWithDemoUser=true, как показано выше.

Апач сервер здесь совсем не используется.

1. Убедитесь что WCS сервер запущен. Вы должны видеть два Linux-процесса

Должны быть порты:
8888 — https dashboard
9091 — http dashboard
8443 — websocket https
8080 — websocket

3. Пройдите по этим портам telnet-ом и убедитесь что они открыты.
Пример:

4. Откройте Dashboard чтобы протестировать Two Way Streaming, нажмите Connect чтобы убедиться, что соединение устанавливается и переходит в ESTABLISHED
Для https
https://host:8888
wss://host:8443
Для http
http://host:9091
ws://host:8080

5. Если вы используете https и wss в браузере Google Chrome и еще не установили SSL сертификат, откройте предварительно страницу https://host:8443 чтобы разрешить браузеру использовать самоподписный сертификат, который отдает сервер по-умолчанию. Скриншоты здесь: https://flashphoner.com/docs/wcs5/w. ide-2/index.html?quick_start_installation.htm

В итоге, вы должны получить ESTABLISHED. Это значит что соединение с сервером установлено и можно двигаться дальше.

1. На первом вложении — все ок.
2. Не могу выполнить команду, пишет что она не найдена
3. telnet проверил, 8080 и 9091 порты открыты
4. Все так же выдает ошибку (вложение №2)

Насчет вот этого «Проверьте, не занят ли порт другим процессом.» Есть предположение, что занят, на этом хостинге в другой папке лежит конструктор мобильных приложений, который наверняка использует Java. Но точно проверить не могу, потому что не запускается команда netstat, где она может еще располагаться?

Источник

I am developing a chat application using Ruby on Rails.
It works fine in the development environment, but gives an error in the production environment.
Probably a server problem.
I ’m glad if you can comment on anything. Thank you.

There are no errors in nginx or unicorn logs.

In the development environment, puma was used, so I think it could have been automatically operated in the middle.

Apparently ActionCable is not working. Others are working.

Error message

google crome console

WebSocket connection to 'wss: // domain/cable' failed: Error during WebSocket handshake: Unexpected response code: 301

Applicable source code

config/environments/prodution.rb

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.
  # Code is not reloaded between requests.
  config.cache_classes = true
  # Eager load code on boot.This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true
  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local = false
  config.action_controller.perform_caching = true
  # Action Cable
  ActionCable.server.config.disable_request_forgery_protection = true
  config.action_cable.allowed_request_origins = ['https: // domain /', /https://domain.*/]
  # Disable serving static files from the `/ public` folder by default since
  # Apache or NGINX already handles this.
  config.public_file_server.enabled = ENV ['RAILS_SERVE_STATIC_FILES']. present?
  # Compress JavaScripts and CSS.
  config.assets.js_compressor =: uglifier
  # config.assets.css_compressor =: sass
  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = false
  # `config.assets.precompile` and` config.assets.version` have moved to config/initializers/assets.rb
  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = 'http://assets.example.com'
  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
  # Mount Action Cable outside main process or domain
  # config.action_cable.mount_path = nil
  # config.action_cable.url = 'wss: //example.com/cable'
  # config.action_cable.allowed_request_origins = ['http://example.com', /http://example.*/]
  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  config.force_ssl = true
  # Use the lowest log level to ensure availability of diagnostic information
  # when problems arise.
  config.log_level =: debug
  # Prepend all log lines with the following tags.config.log_tags = [: request_id]
  # Use a different cache store in production.
  # config.cache_store =: mem_cache_store
  # Use a real queuing backend for Active Job (and separate queues per environment)
  # config.active_job.queue_adapter =: resque
  # config.active_job.queue_name_prefix = "**** _ # {Rails.env}"
  config.action_mailer.perform_caching = false
  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false
  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true
  # Send deprecation notices to registered listeners.
  config.active_support.deprecation =: notify
  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = :: Logger :: Formatter.new
  # Use a different logger for distributed setups.
  # require 'syslog/logger'
  # config.logger = ActiveSupport :: TaggedLogging.new (Syslog :: Logger.new 'app-name')
  if ENV ["RAILS_LOG_TO_STDOUT"]. present?
    logger = ActiveSupport :: Logger.new (STDOUT)
    logger.formatter = config.log_formatter
    config.logger = ActiveSupport :: TaggedLogging.new (logger)
  end
  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false
end

Applicable source code

nginx ***. conf

error_log /var/www/*****/current/log/nginx.error.log;
  access_log /var/www/*****/current/log/nginx.access.log;
  client_max_body_size 2G;
  upstream app_server {
    server unix:/var/www/*****/current/tmp/sockets/.unicorn.sock fail_timeout = 0;
  }
  server {
    listen 80;
    server_name domain;
    keepalive_timeout 5;
    root/var/www/******/current/public;
    try_files $uri/index.html $uri.html $uri @app;
    location @app {
      # HTTP headers
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_pass http: // app_server;
    }
    error_page 500 502 503 504 /500.html;
    location = /500.html {
      root/var/www/*****/current/public;
    }}
  server {
    listen 443 ssl;
    proxy_set_header X-Forwarded-Proto $scheme;
    ssl_certificate /etc/letsencrypt/live/domain/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain/privkey.pem;
    ssl_prefer_server_ciphers on;
    location ^ ~ /.well-known/acme-challenge/ {
            default_type "text/plain";
            root/var/www/******/current/public;
            try_files $uri/index.html $uri.html $uri @app;
    }
    location/{
            proxy_pass http: // domain;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-Forwarded-Proto $scheme;
    }
    location/cable {
            proxy_pass http: // app_server/cable;
            proxy_http_version 1.1;
            proxy_set_header Upgrade websocket;
            proxy_set_header Connection Upgrade;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
  }

Trying

I fiddled with nginx settings and prodution.rb, but could not solve it.
The only error code found is the console.
I referred to the following site, but could not solve it.
Run Rails5 ActionCable (WebSocket) in Puma and nginx in production environment
Deploy Rails5 ActionCable to Nginx and Puma environment
Using ActionCable with AWS, Nginx, Unicorn, and Rails
How to create a real-time chat app with Action Cable (in Rails 5.1.4) ( Part 1) Operate with @heroku!
rails guide
Cannot connect the action cable (upgrade to WebSocket failed)-ruby -on-rails, nginx, ruby-on-rails-5, actioncable
[Rails] Websocket is not connected with Action Cable (cause is config)
Slightly practical Rails ActionCable using Nginx, Redis, MySQL, and iOS/Android Make a sample app to learn the whole picture ~ Backend ~

Supplemental information (FW/tool version etc.)

ruby ​​
rails 5.1.6
ActionCable (websocket)
mysql
capistrano
unicorn
nginx
devise gem
conohaVPS
CentOS8
ssl let’s encrypt

Понравилась статья? Поделить с друзьями:
  • Failed error 0xc004f074 при активации kmsauto
  • Failed error 0xc004f074 kmsauto windows 10
  • Failed error 0xc004f074 kms активатор office
  • Failed error 0xc004f035 при активации kmsauto
  • Failed error 0xc004e015