[nginx] nginx deployment practice - static file + reverse proxy + load balancing +https+websocket

DDGarfield 2022-06-23 19:02:54 阅读数:156

nginxnginxdeploymentpracticestatic

Nginx It's a Russian programmer Igor Sysoev Developed high performance Web and Reverse proxy The server , Also a IMAP/POP3/SMTP proxy server . I heard some time ago Igor Sysoev Taken away by the Russian police , I wonder if it has been released . Speech is normal , Take a look at nginx How to meet our daily needs .

0. Chocolate installation nginx

Because bloggers have windows, So let me introduce you directly windows How to install nginx, If you want to know linux How to install , Please read another article http://www.randyfield.cn/post/2019-06-01-netcore-centos/#3-nginx

Remember CentOs Is there any yum Package manager , that windows Next ? Is there anything so convenient ? The answer is yes ,chocolatey,

chocolatey

  • chocolatey install
Get-ExecutionPolicy
# If you return Restricted
# Just run the following command
Set-ExecutionPolicy AllSigned
# perhaps
Set-ExecutionPolicy Bypass -Scope Process
# Then perform -Paste the follow text into your shell and press Enter
#Wait a few seconds for the command to complete
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
#If you don't see any errors, you are ready to use Chocolatey
  • install nginx
choco install nginx

Here are two points to note

  1. adopt choco install nginx, It will be installed together NSSM, This is a good thing , You can put nginx Registered as windows service , amount to linux Under the Supervisor and PM2
  2. adopt choco install nginx, At the last time, you need to agree to choose y[Yes] Before , Note that the content written back is , He will carry out C:\ProgramData\chocolatey\lib\nginx\tools\chocolateyInstall.ps1 Script
 $toolsDir = Split-Path -parent $MyInvocation.MyCommand.Definition
. "$toolsDir\helpers.ps1"
$pp = Get-PackageParameters
$arguments = @{
packageName = $env:chocolateyPackageName
file = "$toolsDir\nginx-1.17.8.zip"
destination = if ($pp.installLocation) { $pp.installLocation } else { Get-ToolsLocation }
port = if ($pp.Port) { $pp.Port } else { 80 }
serviceName = if ($pp.NoService) { $null } elseif ($pp.serviceName) { $pp.serviceName } else { 'nginx' }
}
if (-not (Assert-TcpPortIsOpen $arguments.port)) {
throw 'Please specify a different port number...'
}
Install-Nginx $arguments

Look for the port That line , you 're right ,80 port ,nginx Default , So before we go on , Please check 80 port Is it occupied , If it is occupied, the installation will fail . What do I do ? This is where you just need to edit the above script , hold 80 Change to a Unused ports . Then go back to the command window and continue , choice Y, You can make it .

For example, I changed it to

 $toolsDir = Split-Path -parent $MyInvocation.MyCommand.Definition
. "$toolsDir\helpers.ps1"
$pp = Get-PackageParameters
$arguments = @{
packageName = $env:chocolateyPackageName
file = "$toolsDir\nginx-1.17.8.zip"
destination = if ($pp.installLocation) { $pp.installLocation } else { Get-ToolsLocation }
port = if ($pp.Port) { $pp.Port } else { 81 }
serviceName = if ($pp.NoService) { $null } elseif ($pp.serviceName) { $pp.serviceName } else { 'nginx' }
}
if (-not (Assert-TcpPortIsOpen $arguments.port)) {
throw 'Please specify a different port number...'
}
Install-Nginx $arguments

Installed nginx stay C:\tools Next , The configuration file will also default to the initialization configuration in the following section

1. Initialize configuration

#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 81;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 81;
# listen 81;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 81 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}

2. Deploy static files

In fact, initialization is a static file deployment

/ Ask to html Under folder index.html file

worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 81;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

3. Deploy Vue Built static file

quote Vue Official documents --”vue-router Default hash Pattern —— Use URL Of hash To simulate a complete one URL, So when URL When the change , The page will not be reloaded . But here url There will be one. #, That can only be changed to history Pattern , But play it well , Background configuration support is also required . Because our application is a single page client application , If the background is not configured correctly , When the user directly accesses in the browser, it will return 404, It's not good . You need to add try_files uri uri/ /index.html;"

try_files The meaning is : First it will match uri file , If you don't match url/ file , If there is no more, I will find /index.html

worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 81;
server_name localhost;
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
#proxy_redirect off;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

4. Reverse proxy

Deploy the front-end and back-end that are separated from the front-end and back-end in the same domain

The backend may be deployed in IIS,Node,Apache wait web The server , But we don't want to be in the front api Hard coded backend in the request url, And if the backend does not add a request header that allows spanning , The browser will also block .

worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 81;
server_name localhost;
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
#proxy_redirect off;
}
location /api/ {
proxy_pass http://ip:port/outside/api/; # Reverse proxy
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_cookie_path /api /;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

That is, when the front end calls the interface http://ip:81/api/ Request , Will be reverse proxied to http://ip:port/outside/api/, If the background does not allow cross domain configuration , Then this method is the solution to cheat the browser .

5. Load balancing

The popularity of front and back end separation mode , In addition to solving the problem of parallel efficiency of front-end and back-end development , Liberation of productive forces , decoupling , In addition to a series of advantages such as rapid positioning problem , Another is horizontal expansion . In the case of large concurrency , Front and back end servers can be expanded horizontally at the same time , This extension uses load balancing .

worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#api Interface deployment to 3 A different place
upstream centerapi{
server 192.168.110.10:82 weight=5;
server 192.168.110.11:82 weight=3;
server 192.168.110.10:83 weight=2;
}
server {
listen 81;
server_name localhost;
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
#proxy_redirect off;
}
location /api/ {
proxy_pass http://centerapi/; # Reverse proxy
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_cookie_path /api /;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
# Expose the address of the reverse proxy
#add_header backendIP $upstream_addr;
#add_header backendCode $upstream_status;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

Here's the request api Interface ,nginx The request will be assigned to the following according to the weight 3 individual url

 upstream centerapi{
server 192.168.110.10:82 weight=5;
server 192.168.110.11:82 weight=3;
server 192.168.110.10:83 weight=2;
}

If you want to test whether each time is a different address , It can make nginx Return the address to which each request is forwarded to the browser and add the following configuration

 # Expose the address of the reverse proxy
add_header backendIP $upstream_addr;
add_header backendCode $upstream_status;

6. Integrated deployment of subsystems

Our company has one ASP.NET MVC Old projects Integration with new projects separated from the front end and the back end

The old project is a platform , Contains several centers , One of the centers is the new project

  • /--- Reverse proxy to IIS The upper part ASP.NET MVC master station
  • ^~/center1--- Front end built static pages , Passed nginx Release
  • ^~/center1/api/--- The front end uses api Interface , Reverse proxy + Load balancing
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream centerapi{
server 192.168.110.10:82 weight=5;
server 192.168.110.11:82 weight=3;
server 192.168.110.10:83 weight=2;
}
server {
listen 80;
server_name 192.168.110.10;
# master station
location / {
proxy_pass http://192.168.110.10/;#ASP.NET MVC master station IIS Deployed
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
# New center front end
location ^~/center1 {
proxy_pass http://192.168.110.10:81/;# Front end built static pages The following configuration
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
# New center api
location ^~/center1/api/ {
proxy_pass http://centerapi/;# Interface called by the front end
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 81;
server_name localhost;
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
#proxy_redirect off;
}
#location /api/ {
#proxy_pass http://centerapi/; # Reverse proxy
#proxy_http_version 1.1;
#proxy_set_header Host $http_host;
#proxy_cookie_path /api /;
#proxy_set_header Upgrade $http_upgrade;
#proxy_set_header Connection keep-alive;
#proxy_cache_bypass $http_upgrade;
# Expose the address of the reverse proxy
#add_header backendIP $upstream_addr;
#add_header backendCode $upstream_status;
#}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

7.Https

The leader said , before iis You can let the website pass https visit , New projects also need ,https need ssl certificate , We all know SSL Certificates only have certificates from large companies , Only browsers will recognize , such as Symantec、Entrust、Geotrust, Otherwise, the untrusted certificate will be reported . But in order to meet the needs of leaders , Or through openssl Relevant certificates have been generated .

worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream centerapi{
server 192.168.110.10:82 weight=5;
server 192.168.110.11:82 weight=3;
server 192.168.110.10:83 weight=2;
}
server {
listen 80;
server_name 192.168.110.10;
#ssl Turn on
ssl on;
ssl_certificate ssl/server.crt;
ssl_certificate_key ssl/server.key;
location / {
proxy_pass http://192.168.110.10/;#ASP.NET MVC master station
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
location ^~/center1 {
proxy_pass http://centerapi/;# Front end built static pages The following configuration
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
location ^~/center1/api/ {
proxy_pass http://192.168.110.10:81/;# Interface called by the front end
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 81;
server_name localhost;
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
#proxy_redirect off;
}
#location /api/ {
#proxy_pass http://centerapi/; # Reverse proxy
#proxy_http_version 1.1;
#proxy_set_header Host $http_host;
#proxy_cookie_path /api /;
#proxy_set_header Upgrade $http_upgrade;
#proxy_set_header Connection keep-alive;
#proxy_cache_bypass $http_upgrade;
# Expose the address of the reverse proxy
#add_header backendIP $upstream_addr;
#add_header backendCode $upstream_status;
#}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

8.Websocket

The system suddenly increased websocket Service for , Direct access ws://ip:port Hard coding of the front-end should be eliminated , therefore nginx Play a role again .

websocket agreement differ http agreement , however websocket Handshake is through http, The communication mode can be improved from http to turn to websocket.

8.1 ws

worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream centerapi{
server 192.168.110.10:82 weight=5;
server 192.168.110.11:82 weight=3;
server 192.168.110.10:83 weight=2;
}
upstream websocket{
server 192.168.110.10:1443 weight=1;
}
server {
listen 80;
server_name 192.168.110.10;
#ssl on;
#ssl_certificate ssl/server.crt;
#ssl_certificate_key ssl/server.key;
location / {
proxy_pass http://192.168.110.10/;#ASP.NET MVC master station
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
location ^~/center1 {
proxy_pass http://centerapi/;# Front end built static pages The following configuration
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
location ^~/center1/api/ {
proxy_pass http://192.168.110.10:81/;# Interface called by the front end
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
#websocket
location ^~/websocket/ {
proxy_pass http://websocket;# Interface called by the front end
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_connect_timeout 4s;
proxy_read_timeout 600;
proxy_send_timeout 12s;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 81;
server_name localhost;
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
#proxy_redirect off;
}
#location /api/ {
#proxy_pass http://centerapi/; # Reverse proxy
#proxy_http_version 1.1;
#proxy_set_header Host $http_host;
#proxy_cookie_path /api /;
#proxy_set_header Upgrade $http_upgrade;
#proxy_set_header Connection keep-alive;
#proxy_cache_bypass $http_upgrade;
# Expose the address of the reverse proxy
#add_header backendIP $upstream_addr;
#add_header backendCode $upstream_status;
#}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

8.2 wss

Under normal circumstances (http Visit website , Interface ), This completes the configuration , But once ssl on, The original ws, Will cause console output

Mixed Content: The page at ‘https://{ domain name }.com/‘ was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint ‘ws://{ip}:{port}/‘. This request has been blocked; this endpoint must be available over WSS.
Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.

The following configuration is required

worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream centerapi{
server 192.168.110.10:82 weight=5;
server 192.168.110.11:82 weight=3;
server 192.168.110.10:83 weight=2;
}
upstream websocket{
server 192.168.110.10:1443 weight=1;
}
server {
listen 80;
server_name 192.168.110.10;
ssl on;
ssl_certificate ssl/server.crt;
ssl_certificate_key ssl/server.key;
ssl_session_timeout 5m;
ssl_session_cache shared:SSL:50m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 SSLv2 SSLv3;
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://192.168.110.10/;#ASP.NET MVC master station
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
location ^~/center1 {
proxy_pass http://centerapi/;# Front end built static pages The following configuration
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
location ^~/center1/api/ {
proxy_pass http://192.168.110.10:81/;# Interface called by the front end
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_cache_bypass $http_upgrade;
}
location ^~/websocket/ {
proxy_pass http://websocket;# Interface called by the front end
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_connect_timeout 4s;
proxy_read_timeout 600;
proxy_send_timeout 12s;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 81;
server_name localhost;
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
#proxy_redirect off;
}
#location /api/ {
#proxy_pass http://centerapi/; # Reverse proxy
#proxy_http_version 1.1;
#proxy_set_header Host $http_host;
#proxy_cookie_path /api /;
#proxy_set_header Upgrade $http_upgrade;
#proxy_set_header Connection keep-alive;
#proxy_cache_bypass $http_upgrade;
# Expose the address of the reverse proxy
#add_header backendIP $upstream_addr;
#add_header backendCode $upstream_status;
#}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

9. common problem

Nginx When forwarding Header Information lost in

adopt Nginx After forwarding , Header in access_token Information loss , After the check , Find out Nginx On Forwarding ,header Underlined in _ The property of does not forward by default , Configuration needs to be added :

server {
listen 80;
server_name 127.0.0.1;
#charset koi8-r;
#access_log logs/host.access.log main;
underscores_in_headers on;
}

Reverse proxy , Operation timeout

Reverse proxy an interface , Interface processing time exceeds 60 second , Will report time out Error of .

 proxy_read_timeout 600;

10. Reference link

https://blog.csdn.net/qq_29663071/article/details/80759098

https://www.nginx.com/blog/websocket-nginx/

https://blog.csdn.net/duyiwuerluozhixiang/article/details/100358930

版权声明:本文为[DDGarfield]所创,转载请带上原文链接,感谢。 https://qdmana.com/2022/174/202206231758266742.html