SoFunction
Updated on 2025-03-02

Sample code for Nginx to configure WebSocket proxy

NginxOfficial document websitenginx documentation

...
http:{
  ...
  server{
    ...
    # WebSocket Agent    location /wsUrl/ {
      rewrite ^/wsUrl/(.*)$ /$1 break; #Intercepting the logo removal      proxy_pass http://192.168.100.20:8080; #Here is http not WS, no doubt, the proxy's IP and port write the actual address of WS access      proxy_http_version 1.1; #http 1.1 must be used here      #The following two must be set, and the request header is set to WS request method      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }
    ...
  }
  ...
}

Official document agent example

http {
    include       ;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    
    map $http_upgrade $connection_upgrade {
		default upgrade;
		''      close;
	}
	
    server {
        listen       9001;
        server_name  localhost;

        location / {
            root   html;
            index   ;
        }

        location ^~ /websocket {
            proxy_pass http://localhost:8090/;
            proxy_http_version 1.1;
            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_read_timeout 120s;

            proxy_set_header Upgrade websocket;
            proxy_set_header Connection Upgrade;
        }
    }
}

Linux View Installation File Command Manual

[!cause]
I used the command whereis nginx to jump out a lot of paths, but I didn't quite understand what each path means, so I took a closer look and found a directory of path /usr/share/man/man8/. The following are usually manual paths. Here you can see the basic command operations of many software. You can use the command man nginx to view nginx. manual.

Nginx log configuration plan

You can refer toDetailed explanation of Nginx access log (access_log) configuration and information

General usemainFormat

as follows

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                       '$upstream_addr $upstream_response_time $request_time ';
access_log  logs/  main;
  • $remote_addr: The IP address of the client.
  • $remote_user: The username of the remote user when using HTTP basic authentication.
  • $time_local: Access time for local time.
  • $request: Content requested by the client.
  • $status: HTTP status code for the server response.
  • $body_bytes_sent: The number of bytes sent to the client, excluding the size of the response header.
  • $http_referer: The URL of the reference page.
  • $http_user_agent: User-Agent string of the client, information identifying the client's browser and operating system, etc.
  • $http_x_forwarded_for: X-Forwarded-For header, used to identify the IP address of the original client, used when requesting to pass through the proxy server.
  • $upstream_addr: The IP address of the backend (upstream) server.
  • $upstream_response_time: Time to receive responses from the backend server.
  • $request_time: The total time the client initiates the request to receive the response.

[!mistake]
When configuring nginx logs, I didn't know where to place the log_format main configuration, so I put it on the outermost layer, resulting in an error message nginx: [emerg] "log_format" directive is not allowed here in /etc/nginx/:14 The solution is to place log_format main in http {} to solve the problem

Solve the problem successfully – Use Nginx proxy WebSocket

The specific configuration is as follows, the function implemented is to send all to10.6.30.185:9001To match the requesturlIs there any in it?/websocketThis level, if available, use itWebSocketRequest sent to10.6.3.46:8001, 6 servers were used to perform one laternginxactingWebSocketIn operations, information can be read in the background, and the background can also push information.

user nobody;  
worker_processes  6;  
  
  
#nginx enables multi-core settings. Currently, the 185 machines are all 6 cores.worker_cpu_affinity 000001 000010 000100 001000 010000 100000;  
#error_log  logs/;  
#error_log  logs/  notice;  
#error_log  logs/  info;  
  
  
error_log  /var/log/nginx/ info;  
  
#Process Filepid        /var/run/;  
  
worker_rlimit_nofile 1024;  
  
events {  
    use epoll; # Modify here    worker_connections  1024;  
}

# Set up the http serverhttp {  
    include       ; #File extension and file type mapping table    default_type  application/octet-stream; #Default file type    charset utf-8; #Default encoding    fastcgi_connect_timeout 2000;  
    fastcgi_send_timeout 2000;  
    fastcgi_read_timeout 2000;  
    client_max_body_size 1024m;  
    sendfile on;  
    tcp_nopush on;  
    tcp_nodelay on;  
    keepalive_timeout 120;  
    gzip  on;  
    limit_req_zone $binary_remote_addr zone=test:10m rate=10r/s;  
  
    #Log Configuration    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '  
                          '$status $body_bytes_sent "$http_referer" '                          '"$http_user_agent" "$http_x_forwarded_for"'                           '$upstream_addr $upstream_response_time $request_time ';  
            #$remote_addr: The IP address of the client.            #$remote_user: The username of the remote user when using HTTP basic authentication.            #$time_local: Access time for local time.            #$request: The content requested by the client.            #$status: HTTP status code for the server response.            #$body_bytes_sent: The number of bytes sent to the client, excluding the size of the response header.            #$http_referer: The URL of the reference page.            #$http_user_agent: The User-Agent string of the client, which identifies the client's browser and operating system and other information.            #$http_x_forwarded_for: X-Forwarded-For header, used to identify the IP address of the original client, and used when requesting to pass through the proxy server.            #$upstream_addr: The IP address of the backend (upstream) server.            #$upstream_response_time: The time to receive the response from the backend server.            #$request_time: The total time the client initiates the request to receive the response.    access_log /var/log/nginx/ main;
	map $http_upgrade $connection_upgrade {  
	    default upgrade;  
	    ''      close;  
	}
    server {  
        listen 9001;  
        server_name  10.6.30.185;  
        location ^~ /websocket {  
            proxy_pass http://10.6.3.46:8001;  
            proxy_http_version 1.1;  
            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_read_timeout 120s;  
            proxy_set_header Upgrade $http_upgrade;  
            proxy_set_header Connection $connection_upgrade;  
        }  
    }  
}

Probable problems

  • The IP from the same gateway may be repeated, so if I want to make a specific connectionWebSocket IPIn the collection,keyMust bemacaddressvalueYes `Connected object information
  • Can specify the need to send messages

This is the article about Nginx's sample code for configuring WebSocket Agent. For more information about Nginx WebSocket Agent, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!