Cross domain problems caused by the same source strategy can be easily solved! What kind of magic is this

Posted by benkillin on Tue, 25 Jan 2022 23:42:43 +0100

Nginx concept

  • Nginx is a high performance HTTP server, reverse proxy server and email (IMAP/POPP3) proxy server Developed by Igor Sysoev of Russia, nginx can support 50000 concurrent links, with very low CPU, memory and other resource consumption and stable operation

Nginx application scenario

  • HTTP server, virtual host: Nginx is an HTTP service. It can provide HTTP services independently. It can be used as a static web server. It can virtualize multiple websites on one server, such as the virtual host used by personal websites
  • Reverse proxy: when the number of visits to the website reaches a certain level and a single server cannot meet the user's request, Nginx can be used as the reverse proxy when multiple server clusters are needed
  • Load balancing: multiple servers can share the load equally, and a server will not be idle due to high load downtime of a server

HTTP server, virtual host

  • Use Docker to install and run Nginx in/ Create Nginx in conf Conf file, configure Docker compose yml
version: '3.1'
services: 
 nginx:
  restart: always
  image: nginx
  container_name: nginx
  ports:
   - 80:80
  volumes:
   - ./conf/nginx.conf:/etc/nginx/nginx.conf	
   - ./wwwroot:/usr/share/nginx/wwwroot
  • Virtual host: virtual host is a special software and hardware technology Each computer on the network can be divided into multiple virtual hosts. Each virtual host can independently provide www services. In this way, one host can provide multiple web services. Each virtual host is independent and does not affect each other
  • The configuration of virtual hosts can be realized through nginx. Nginx supports the configuration of three types of virtual hosts:
    • IP based virtual host
    • Domain name based virtual host
    • Port based virtual host
  • Nginx configuration file structure: each server is a host
events {
}

http {
	server{
	}

	server{
	}
}
Domain name based virtual host configuration
  • Requirements:
    • Two domain names point to the same Nginx server. Users access different domain names and display different web page contents
    • The two domain names are admin service. itoken. oxford. COM and Admin web. itoken. oxford. com
    • The Nginx server uses virtual machine 192.168.32.255
  • Configure Windows Hosts file:
    • Modify the window s hosts file (C:/Windows/System32/drivers/etc)-SwitchHosts
    • Specify admin. From the host file service. itoken. oxford. COM and Admin web. itoken. oxford. Com corresponds to 192.168.32.255 virtual machine
  • Create directories and files: create htmlservice and htmlweb directories in / usr/local/docker/nginx/wwwroot directory, and create index. XML HTML file
  • Configure virtual host: modify nginx.com in / usr/local/docker/nginx/conf directory Conf configuration file
user nginx;
worker_processes 1;

events {
	worker_connections 1024;
}

http{
	include				mime.type;
	default_type	application/octet-stream;

	sendfile			on;

	keepalive_timeout	65;
	
	server{
		listen 				80;
		server_name	admin.service.itoken.oxford.com
		# All requests start with / and all requests can match this location
		location / {
			root  /usr/local/docker/nginx/wwwroot/htmlservice;
			# Specify the welcome page and find it from left to right
			index index.html index.htm;
		} 
	}

	server{
		listen 					80;
		server_name		admin.web.itoken.oxford.com

		location / {
			root /usr/share/nginx/wwwroot/htmlweb;
			index index.html index.htm;
		}
	}	
}
Port based virtual host configuration
  • Requirements:
    • Nginx provides monitoring services on ports 80 and 8080
    • If port 80 is requested, HTML in the html80 directory is requested
    • Request port 8080, then request HTML in html8080 directory
  • Create directories and files: create html80 and html8080 directories under / usr/local/docker/nginx/wwwroot directory, and create two indexes respectively HTML file
  • Configure virtual host: modify nginx.com in / usr/local/docker/nginx/conf directory Conf configuration file
worker_processes 1;

events {
	worker_connections 1024;
}

http{
	include				mime.type;
	default_type	application/octet-stream;

	sendfile			on;

	keepalive_timeout	65;
	
	# Configure virtual host 192.168.32.255
	server{
		# Listen to the IP and port. Configure 192.168.32.255:80
		listen 				80;
		# Virtual host name, IP address configured here
		server_name	192.168.32.255;
		# All requests start with / and all requests can match this location
		location / {
			# Use the root command to specify the virtual host directory, that is, the web page storage directory
			# For example: access http://ip/index.html You will find / usr / local / docker / nginx / wwwroot / html80 / index html
			# For example: access http://ip/item/index.html You will find / usr / local / docker / nginx / wwwroot / html80 / item / index html
			root  /usr/share/nginx/wwwroot/html80;
			# Specify the welcome page and find it from left to right
			index index.html index.htm;
		} 
	}

	# Configure virtual host 192.168.32.255
	server{
		listen 					8080;
		server_name		192.168.32.255;

		location / {
			root /usr/share/nginx/wwwroot/html8080;
			index index.html index.htm;
		}
	}
}

Nginx reverse proxy

proxy server

When the client sends a request, it will not send it directly to the destination host Instead, it is sent to the proxy server first. After receiving the client request, the proxy server sends it to the host, receives the data returned by the destination host, stores it in the hard disk of the proxy server, and then sends it to the client

Role of proxy server
  • Improve access speed: since the data returned by the target host is stored in the hard disk of the proxy server, the next time the customer accesses the same site data, it will directly read it from the hard disk of the proxy server, which plays a role of cache, especially for popular sites, it can significantly improve the request speed
  • Firewall function: since all client requests must access the remote site through the proxy server, restrictions can be set on the proxy server to filter out some unsafe information
  • Access to inaccessible target sites through proxy servers: there are many open proxy servers on the Internet. When access is limited, clients can access the target sites through unrestricted proxy servers
Forward proxy

It is set up between the client and the target host. It is only used to proxy the connection request from the internal network to the Internet. The client must specify a proxy server and send the http request originally sent directly to the web server to the proxy server

Reverse proxy

The reverse proxy server is set up on the server side to alleviate the workload of the server by buffering the frequently requested pages, forward the client request to the target server on the internal network, and return the results obtained from the server to the client requesting connection on the Internet. At this time, the proxy server and the target host appear as a server together

Reverse proxy application
  • Prevent vicious attack of external network on internal network server
  • Cache to reduce server stress
  • Access security control
  • Perform load balancing and distribute user requests to multiple servers
Nginx reverse proxy Tomcat
  • Start Tomcat container: start two Tomcat containers with mapping ports 9090 and 9091, and configure docker compose yml
version: '3'
services:
 tomcat1:
  image: tomcat
  container_name: tomcat1
  ports:
   - 9090:8080
 tomcat2:
  image: tomcat
  container_name: tomcat2
  ports:
   - 9091:8080
  • Configure Nginx reverse proxy: modify Nginx.com in / usr/local/docker/nginx/conf directory Conf configuration file
user nginx;
worker_processes 1;

events {
	worker_connection	1024;
}

http {
	include				mime.type;
	default_type	application/octet-stream;

	sendfile 			on;

	keepalive_timeout	65;

	# Configure a tomcat1 proxy server
	upstream tomcat_server1 { 
		server 192.168.32.255:9090;
	}

	# Configure a tomcat2 proxy server
	upstream tomcat_server2{ 
		server 192.168.32.255:9091;
	}

	server {
		listen 		80;
		server_name	admin.service.itoken.oxford.com
		# All requests start with / and all requests can match this location
		location / {
			# Domain name admin service. itoken. oxford. All requests from com are forwarded to tomcat_server1, i.e. tomcat1 server
			proxy_pass http://tomcat_server1;
			# Welcome page, find pages from left to right
			index index.jsp index.html index.htm;
		} 
	}

	server{
		listen 			80;
		server_name		admin.web.itoken.oxford.com

		location / {
			# Domain name admin web. itoken. oxford. All requests from com are forwarded to tomcat_server2, i.e. tomcat2 server
			proxy_pass http://tomcat_server2;
			index index.jsp index.html index.htm;
		}
	}	
}

Nginx load balancing

load balancing
  • Based on the existing network structure, load balancing provides a cheap, effective and transparent method to expand the bandwidth of network equipment and servers, increase throughput, strengthen network data processing capacity, and improve the flexibility and availability of the network
  • Load balance is distributed to multiple operating units for execution, such as Web server, FTP server, enterprise key application server and other key task servers, so as to jointly complete work tasks
Nginx for load balancing
  • Requirements:
    • As a load balancing server, nginx first arrives at nginx and then forwards the request to tomcat server according to the load balancing configuration
    • nginx load balancing server: 192.168.32.255:80
    • tomcat server: 192.168.32.255:9090
  • Configure load balancing for Nginx: modify Nginx.com under / usr/local/docker/nginx/conf Conf configuration file
user nginx;
worker_processes 1;

events {
	worker_connection	1024;
}

http {
	include				mime.type;
	default_type	application/octet-stream;

	sendfile 			on;

	keepalive_timeout	65;

	upstream myapp {
  		server 192.168.32.255:9090 weight=10;
  		server 192.168.32.255:9091 weight=10;
	}

	server{
		listen			80;
		server_name		nginx.oxford.com;
		location / {
			proxy_pass	http://myapp;
			index		index.jsp index.html index.htm;
		}
	}
}

Nginx solves cross domain problems

Cross domain problem

  • Cross domain problems occur when Ajax requests are made on the browser side
  • Cross domain: the browser cannot execute scripts from other websites It is caused by the browser's homology policy and the security restrictions imposed by the browser on JavaScript

Homology

  • Homology: domain name, protocol and port are the same

Ways to solve cross domain problems

Using CORS (cross resource sharing) to solve cross domain problems
  • CORS is the W3C standard, fully known as "cross origin resource sharing", which allows browsers to send XMLHttpRequest requests to cross source servers, thus overcoming the limitation that Ajax can only be used in the same source
  • CORS requires both browser and server support
  • At present, all browsers support this function, and IE browser cannot be lower than IE10
  • The whole CORS communication process is completed automatically through the browser without user participation For developers, there is no difference between CORS communication and homologous Ajax communication, and the code is exactly the same
  • Once the browser finds that Ajax requests cross the source, it will automatically add some additional header information. Sometimes there will be an additional request, but the user will not feel it
  • The key to realize CORS communication is the server. As long as the server implements CORS interface, it can communicate across domains
  • Set: access control allow origin in the header (annotate the controller class in the server request controller with @ CrossOrigin(value = "*") annotation)
Using JSONP to solve cross domain problems
  • Jsonp: (JSON with padding), a "usage mode" of JSON, can be used to solve the problem of cross domain data access of mainstream browsers
  • Due to the same origin policy, server1.0 is generally used example. Com's web page cannot be connected with server2 example. The < script > element of HTML is an exception
  • Using the open strategy of < script > element, web pages can get JSON data dynamically generated from other sources, and this mode is called JSONP
  • The data captured with JSONP is not JSON, but arbitrary JavaScript, which is executed with a JavaScript translator rather than parsed with a JSON parser
  • A callback function is required for the target server
  • Comparison between CORS and JSONP:
    • CORS is used for the same purpose as JSON, but it is more powerful than JSONP
    • CORS supports all types of HTTP requests
    • JSONP only supports GET requests. The advantages of JSON are that it supports old-fashioned browsers and can request data from websites that do not support CORS

Nginx reverse proxy solves cross domain problems

  • When the server cannot set the header or provide the callback function, it can use Nginx reverse proxy to solve the cross domain problem
Nginx configuration cross domain
  • Nginx in / usr/local/docker/nginx/conf Add configuration (Get: font cross domain) to the location in conf:
add_header Access-Control-Allow-Origin *Or domain name;
add_header Access-Control-Allow-Headers X-Requested-with;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
  • Configure nginx in / usr/local/docker/nginx/conf Conf configuration file (POST: upload file):
user nginx;
worker_processes 1;

events {
	worker_connection 1024;
}

http {
	include				mime.types;
	default_type		application/octet-stream;

	sendfile			on;

	keepalive_timeout 	65;

	server {
		listen			80;
		server_name		upload.myshop.com;
		add_header 'Access-Control-Allow-Origin' '*';
		add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-with,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
		location / {
			proxy_pass	http://192.168.32.255:8888;
			if($request_method = 'OPTIONS'){
				add_header Access-Control-Allow-Origin *;
				add_header Access-Control-Allow-Headers X-Requested-with;
				add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,PATCH,OPTIONS;
				# Solve the problem of false request. If it is a simple request, there is no problem. Here is the file upload. The first request is in OPTIONS mode, and the actual request is in POST mode
				add_header Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-with,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range;
				return 200;
			}
		}
	}
}