search
HomeOperation and MaintenanceNginxHow to configure nginx reverse proxy webSocket

How to configure nginx reverse proxy webSocket

May 21, 2023 pm 12:13 PM
nginxwebsocket

Because the websocket protocol is upgraded based on the http protocol (see the figure below), you can use nginx reverse proxy websocket.

How to configure nginx reverse proxy webSocket

websocket

From As can be seen from this picture, the websocket connection is established based on the http protocol.

get /chat http/1.1
host: server.example.com
upgrade: websocket
connection: upgrade
sec-websocket-key: x3jjhmbdl1ezlkh9gbhxdw==
sec-websocket-protocol: chat, superchat
sec-websocket-version: 13
origin: http://example.com

Children who are familiar with http may have noticed that there are just a few more things in this handshake request similar to the http protocol.

upgrade: websocket
connection: upgrade
这个就是websocket的核心了,告诉apache、nginx等服务器:我发起的是websocket协议。
sec-websocket-key: x3jjhmbdl1ezlkh9gbhxdw==
sec-websocket-protocol: chat, superchat
sec-websocket-version: 13

First of all, sec-websocket-key is a base64 encode value, which is randomly generated by the browser. It tells the server: Peat, don’t fool me, I want to verify whether you are really a websocket assistant. .

Finally, sec-websocket-version tells the server the websocket draft (protocol version) used. At the beginning, the websocket protocol was still in the draft stage, and there were all kinds of weird protocols, and there were also There are many strange and different things. Firefox and Chrome use different versions. At the beginning, there were too many websocket protocols, which was a big problem. . But it’s okay now, it’s settled. A thing that everyone uses

Then the server will return the following things, indicating that the request has been accepted and the websocket has been successfully established!

http/1.1 101 switching protocols
upgrade: websocket
connection: upgrade
sec-websocket-accept: hsmrc0smlyukagmm5oppg2hagwk=
sec-websocket-protocol: chat

This is the last area that http is responsible for. Tell the client that I have successfully switched the protocol~

upgrade: websocket
connection: upgrade

is still fixed, telling the client that the upcoming upgrade is the websocket protocol. At this point, http has completed all its work, and the next step is to proceed completely in accordance with the websocket protocol.

Once you understand the principle of the protocol, you can proceed to the next step

First, nginx configures the https certificate

The server certificate is configured by the boss , I used it directly. Check it yourself if needed. 0.0

Add the following configuration to the service node in the nginx configuration file

location /wss
    {
         proxy_pass http://127.0.0.1:8888;
         proxy_http_version 1.1;
         proxy_set_header upgrade $http_upgrade;
         proxy_set_header connection "upgrade";
        proxy_set_header x-real-ip $remote_addr;
     }

Explain the parameters

/wss This is randomly set up. It tells nginx the URL to be proxied. Now my setting is wss. When I visit my server https:// abc.com/wss, nginx will map my request to the local port 8888.

proxy_pass The URL you want to proxy to, my proxy is to port 8888 of this machine.

proxy_http_version The http version used when proxying.

Here comes the key point:

Key parameters of proxy websocket

proxy_set_header upgrade Change the http request header when proxying upgrade Set to the request header of the original http request, and the request header of the wss protocol is websocket
proxy_set_header connection Because of the proxy wss protocol, the http request header is connection Set to upgrade

##proxy_set_header x-real-ip Set the ip of the original http request to the proxy and fill in $ remote_addr That's it

As for the response parameters of the websocket protocol, you don't need to worry about it during reverse proxy.

At this point, the configuration of nginx reverse proxy websocket is completed. Restart nginx, try to connect with websocket, and fill in the original wss address

wss://abc.com/wss. If the websocket is successfully connected, it means that the nginx reverse proxy websocket has been successful.

Summary

The current configuration is only the configuration when reverse proxying to this machine. If you want to reverse proxy to other hosts, the proxy may cross domains. The problem is that cross-domain configuration needs to be done in the reverse proxy of nginx.

Thinking

You can see this paragraph in the configuration file of nginx

location ~ .php$ {
   root html;
   fastcgi_pass 127.0.0.1:9000;
   fastcgi_index index.php;
   fastcgi_param script_filename $document_root$fastcgi_script_name;
   include fastcgi_params;
}

This is the configuration file of php in nginx, let me delete it, how? It looks so familiar, this configuration list is so similar to the websocket reverse proxy just now. I found out by searching the Internet that when nginx handles PHP type requests, it sends the request to the fastcgi management process. The fascgi management process selects the cgi sub-process processing result and returns it to nginx, and php-fpm is a PHP fastcgi manager. nginx itself cannot handle PHP. It is just a web server. When a request is received, if it is a PHP request, it is sent to the PHP interpreter for processing and the result is returned to the client. Therefore, when nginx handles PHP type requests, it is essentially implemented through the reverse proxy function.

We can expand our thinking and use nginx reverse proxy to achieve more functions, such as proxy tomcat

location /tomcat
    {
         proxy_pass http://127.0.0.1:8080;
         proxy_http_version 1.1;
        proxy_set_header x-real-ip $remote_addr;
     }

The above is the detailed content of How to configure nginx reverse proxy webSocket. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX vs. Apache: Performance, Scalability, and EfficiencyNGINX vs. Apache: Performance, Scalability, and EfficiencyApr 19, 2025 am 12:05 AM

NGINX and Apache are both powerful web servers, each with unique advantages and disadvantages in terms of performance, scalability and efficiency. 1) NGINX performs well when handling static content and reverse proxying, suitable for high concurrency scenarios. 2) Apache performs better when processing dynamic content and is suitable for projects that require rich module support. The selection of a server should be decided based on project requirements and scenarios.

The Ultimate Showdown: NGINX vs. ApacheThe Ultimate Showdown: NGINX vs. ApacheApr 18, 2025 am 12:02 AM

NGINX is suitable for handling high concurrent requests, while Apache is suitable for scenarios where complex configurations and functional extensions are required. 1.NGINX adopts an event-driven, non-blocking architecture, and is suitable for high concurrency environments. 2. Apache adopts process or thread model to provide a rich module ecosystem that is suitable for complex configuration needs.

NGINX in Action: Examples and Real-World ApplicationsNGINX in Action: Examples and Real-World ApplicationsApr 17, 2025 am 12:18 AM

NGINX can be used to improve website performance, security, and scalability. 1) As a reverse proxy and load balancer, NGINX can optimize back-end services and share traffic. 2) Through event-driven and asynchronous architecture, NGINX efficiently handles high concurrent connections. 3) Configuration files allow flexible definition of rules, such as static file service and load balancing. 4) Optimization suggestions include enabling Gzip compression, using cache and tuning the worker process.

NGINX Unit: Supporting Different Programming LanguagesNGINX Unit: Supporting Different Programming LanguagesApr 16, 2025 am 12:15 AM

NGINXUnit supports multiple programming languages ​​and is implemented through modular design. 1. Loading language module: Load the corresponding module according to the configuration file. 2. Application startup: Execute application code when the calling language runs. 3. Request processing: forward the request to the application instance. 4. Response return: Return the processed response to the client.

Choosing Between NGINX and Apache: The Right Fit for Your NeedsChoosing Between NGINX and Apache: The Right Fit for Your NeedsApr 15, 2025 am 12:04 AM

NGINX and Apache have their own advantages and disadvantages and are suitable for different scenarios. 1.NGINX is suitable for high concurrency and low resource consumption scenarios. 2. Apache is suitable for scenarios where complex configurations and rich modules are required. By comparing their core features, performance differences, and best practices, you can help you choose the server software that best suits your needs.

How to start nginxHow to start nginxApr 14, 2025 pm 01:06 PM

Question: How to start Nginx? Answer: Install Nginx Startup Nginx Verification Nginx Is Nginx Started Explore other startup options Automatically start Nginx

How to check whether nginx is startedHow to check whether nginx is startedApr 14, 2025 pm 01:03 PM

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

How to close nginxHow to close nginxApr 14, 2025 pm 01:00 PM

To shut down the Nginx service, follow these steps: Determine the installation type: Red Hat/CentOS (systemctl status nginx) or Debian/Ubuntu (service nginx status) Stop the service: Red Hat/CentOS (systemctl stop nginx) or Debian/Ubuntu (service nginx stop) Disable automatic startup (optional): Red Hat/CentOS (systemctl disabled nginx) or Debian/Ubuntu (syst

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment