Common problems and solutions of nginx

https reverse proxy configuration

● the fixed port number of HTTPS is 443, which is different from port 80 of HTTP
● the SSL standard requires the introduction of security certificates, so in nginx In conf, you need to specify the certificate and its corresponding key
Others are basically the same as http reverse proxy, but the configuration in the Server part is somewhat different

  #HTTP server
  server {
      #Listen to port 443. 443 is a well-known port number, which is mainly used for HTTPS protocol
      listen       443 ssl;

      #Definition use www.xx.com Com visit
      server_name  www.helloworld.com;

      #ssl certificate file location (common certificate file format: crt/pem)
      ssl_certificate      cert.pem;
      #ssl certificate key location
      ssl_certificate_key  cert.key;

      #ssl configuration parameters (optional configuration)
      ssl_session_cache    shared:SSL:1m;
      ssl_session_timeout  5m;
      #Digital signature, MD5 is used here
      ssl_ciphers  HIGH:!aNULL:!MD5;
      ssl_prefer_server_ciphers  on;

      location / {
          root   /root;
          index  index.html index.htm;
      }
  }

Static file configuration

Sometimes we need to configure static files (that is, html files and a bunch of static resources)

For example: if all static resources are placed in the / app/dist directory, we only need to be in nginx You can specify the home page and the host of the site in conf.

The configuration of static resources cannot be written in the same location as the dynamic access path

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    gzip on;
    gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/javascript image/jpeg image/gif image/png;
    gzip_vary on;

    server {
        listen       80;
        server_name  localhost;
		#The configuration of static resources cannot be written in the same location as the dynamic access path
        location / {
            root /app/dist;
            index index.html;
            #Forward any requests to index html
        }
    }
}

The service obtains the real IP address of the client

When you use the nginx reverse server, use request on the web side Getremoteaddr() (essentially get) r e m o t e a d d r ) , take have to of yes n g i n x of land site , Namely remote_addr) to get the address of nginx, i.e remotea (ddr) is the address of nginx, i.e. remote_ The addr variable encapsulates the address of nginx. Of course, it is impossible to obtain the user's real ip. However, nginx can obtain the user's real ip, that is to say, nginx uses $remote_ The addr variable obtains the user's real ip. If we want to obtain the user's real ip on the web, we must make an assignment here in nginx, as follows:

proxy_set_header            X-real-ip $remote_addr;
 proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;

Among them, the X-real-ip is a custom variable name, which can be taken at will. After that, the user's real IP will be placed in the X-real-ip variable, and then it can be obtained on the web:

#Use this to get the client ip directly
ipAddress =request.getHeader("X-real-ip")

Or use this:
ipAddress = request.getHeader("x-forwarded-for");

But use request.getHeader("x-forwarded-for");This method needs to be segmented, because if a request passes through multiple agents, the obtained ipAddress,There will be more ip,The first is the reality of the client ip,:
  // For the case of passing through multiple agents, the first IP is the real IP of the client, and multiple IPS are divided according to ','
  				//"***.***.***.***".length()
            if (ipAddress != null && ipAddress.length() > 15) { 
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }

Refer to configuration for details

server {
 
        listen       88;
 
        server_name  localhost;
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        location /{
 
            root   html;
 
            index  index.html index.htm;
 
                            proxy_pass                  http://backend; 
 
           proxy_redirect              off;
 
           proxy_set_header            Host $host;
 
           proxy_set_header            X-real-ip $remote_addr;
 
           proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;
 

        }

Cross domain solutions

Cross domain is not that the request cannot be sent out, but that the server returns the result normally and is intercepted by the browser. (in order to prevent non homologous requests from getting the returned data results from the server)
In the development of web domain, the front end and back end separation mode is often used. In this mode, the front end and the back end are independent web applications respectively. For example, the back end is a Java program and the front end is a React or Vue application

Example: www.helloworld.com Com website is composed of a front-end app and a back-end app. The front-end port number is 9000 and the back-end port number is 8080.
If the front-end and back-end use http to interact, the request will be rejected because there is a cross domain problem. Let's see how nginx solves this problem:

First, create enable cors. Com in the nginx/conf directory Conf file, and then set cors:

# allow origin list
set $ACAO '*';

# set single origin
if ($http_origin ~* (www.helloworld.com)$) {
  set $ACAO $http_origin;
}

if ($cors = "trueget") {
    add_header 'Access-Control-Allow-Origin' "$http_origin";
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}

if ($request_method = 'OPTIONS') {
  set $cors "${cors}options";
}

if ($request_method = 'GET') {
  set $cors "${cors}get";
}

if ($request_method = 'POST') {
  set $cors "${cors}post";
}


Then nginx Reference in conf:

# ----------------------------------------------------
# This file is a project nginx configuration fragment
# You can directly include in nginx config (recommended)
# Or copy to the existing nginx and configure it yourself
# www.helloworld.com domain name should be configured with dns hosts
# Among them, the api enables cors, which needs to be matched with another configuration file in this directory
# ----------------------------------------------------
upstream front_server{
  server www.helloworld.com:9000;
}
upstream api_server{
  server www.helloworld.com:8080;
}

server {
  listen       80;
  server_name  www.helloworld.com;

  location ~ ^/api/ {
    include enable-cors.conf;
    proxy_pass http://api_server;
    rewrite "^/api/(.*)$" /$1 break;
  }

  location ~ ^/ {
    proxy_pass http://front_server;
  }
}

Solve the problem that tomcat+nginx static resources cannot be accessed

When using Nginx to realize Tomcat load balancing, the project is released to tomcat, and Nginx is also configured,
During the visit, it was found that it was not as expected
As follows:
Static resource loading failed
Link jump address error
Here is my wrong configuration file

#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;


    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    
    upstream web{
        server localhost:8091;
    }
    

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   /home/ftpuser;
        }

        #error_page  404              /404.html;
    }
    
    server {
        listen            808;
        server_name     localhost;
        
        location /{
            proxy_pass    http://web;
        }

    }

}

Solution:
In the configuration file of Nginx, Nginx Add the following configuration where the server is configured in conf
Note proxy_pass must be configured by upstream, not http://localhost:8091 ;

location ~ .* {
            proxy_pass     http://The name of your upstream configuration;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Fonwarded-For $proxy_add_x_forwarded_for;
        }

This is the correct nginx configuration file after my configuration for reference,

#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;
    #access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #gzip  on;
	
	upstream web{
		server localhost:8091;
	}
	
    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;

        location / {
            root   /home/ftpuser;
        }
        #error_page  404              /404.html;
    }
	
	server {
		listen			808;
		server_name 	localhost;
		
		location /{
			proxy_pass	http://web/;
		}
		
		location ~ .* {
			proxy_pass 	http://web;
			proxy_set_header Host $http_host;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header X-Fonwarded-For $proxy_add_x_forwarded_for;
		}
	}
}

That's it

Keywords: Java Nginx SSL https

Added by elfeste on Thu, 27 Jan 2022 21:05:13 +0200