Matthew Adams
Matthew Adams

Reputation: 2197

How do I fix this Nginx configuration to properly proxy WebSocket requests instead of returning a 301?

Nginx noob. Trying to configure Nginx to act as an SSL proxy server in front of another web server running at http://localhost:8082. That is, I want all requests to http://localhost to be redirected to https://localhost. That part is working just fine.

Problem is, the app on port 8082 also uses WebSocket connections at ws://localhost:8082/public-api/repossession-requests-socket. I'm trying to redirect any connections to ws://localhost/public-api/repossession-requests-socket to wss://localhost/public-api/repossession-requests-socket and have Nginx proxy those WebSocket requests to ws://localhost:8082/public-api/repossession-requests-socket.

Instead, the WebSocket connections are failing because Nginx is returning a 301 for both ws://localhost/public-api/repossession-requests-socket & wss://localhost/public-api/repossession-requests-socket. My configuration is below; I'm using the Docker image nginx:alpine in my tests ($PWD is mapped to /app).

How do I need to change this so that I no longer see 301s?

events {
  worker_connections 1024;
}

http {
    server {
        listen 80;
        return 301 https://$host$request_uri;
    }

    server {
        listen 443;
        server_name localhost;

        ssl_certificate /app/docker/public.pem;
        ssl_certificate_key /app/docker/private.pem;

        ssl on;
        ssl_session_cache builtin:1000 shared:SSL:10m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
        ssl_prefer_server_ciphers on;

        access_log /app/access-443.log;

        location / {
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;

          proxy_pass http://localhost:8082;
          proxy_read_timeout 90;

          proxy_redirect http://localhost:8082 https://localhost;
        }
        location /public-api/repossession-requests-socket/ {
            proxy_pass http://localhost:8082;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }
}

Upvotes: 3

Views: 731

Answers (1)

Matthew Adams
Matthew Adams

Reputation: 2197

Found the problem. The trailing slash on the end of the location stanza.

location /public-api/repossession-reqeuests-socket/ should have been location /public-api/repossession-reqeuests-socket.

Upvotes: 1

Related Questions