Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx config, websocket proxy, location, if

I have a very specific nginx config question:

I need nginx to:

  • proxy websocket connections @ /
  • respond with index.html for standard http requests @ /

This is the closest I can get:

  location = / {
   if ($http_upgrade != "websocket") {
    # Here lies my problem:
    # This returns a http: 302 where i just need it to return the contents
    # of index.html
    return https://admin.permaconn.com/index.html;
   }

   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
   proxy_pass http://localhost:8080;
  }

I am undergoing a structural change with my app from using nodejs as a front proxy to nginx as a front end proxy.

I must configure nginx this way due to expected behaviour from numerous programs already installed devices (aka legacy).

like image 459
Roderick Obrist Avatar asked Mar 27 '26 11:03

Roderick Obrist


1 Answers

You are misusing the return directive.

location = / {
    index index.html;

    if ($http_upgrade = "websocket") {
        proxy_pass http://localhost:8080;  
    }

    proxy_http_version 1.1;
    proxy_set_header Upgrade websocket;
    proxy_set_header Connection upgrade;
}

Docs:

  • http://nginx.org/r/if
  • http://nginx.org/r/index
like image 63
VBart Avatar answered Mar 30 '26 00:03

VBart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!