What is the CORS

CORS is a W3C standard, which stands for Cross-Origin Resource Sharing. It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source.

Almost all current browsers (Internet Explorer 8+, Firefox 3.5+, Safari 4+ and Chrome 3+ support AJAX cross-domain calls through a protocol called Cross-Origin Resource Sharing.

Chrome, Firefox, Opera, and Safari all use XMLHttpRequest2 object, IE use XDomainRequest.

Simply put, a cross-domain target server returns a series of Headers to control whether or not it agrees to cross-domain. Cross-domain resource sharing (CORS) is also the standard solution for future cross-domain problems.

CORS provides the following Headers, Request, and Response packages.

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Credentials
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers
  • Access-Control-Expose-Headers
  • Access-Control-Max-Age

  • Access-Control-Request-Method
  • Access-Control-Request-Headers

One of the most sensitive is the Access-Control-Allow-Origin Header, which is used in the W3C standard to check whether a cross-domain request can be approved. Access Control (Check). If you need to cross domains, the solution is to add access-Control-Allow-Origin to the header of the resource to specify which domain you authorize.

Enable the CORS request

Suppose your application is already on example.com and you want to extract data from www.example2.com. Normally, if you try to make this type of AJAX call, the request will fail and the browser will get a source mismatch error. With CORS, a request from example.com can be allowed simply by adding an HTTP Response header to the www.example2.com server.

Add access-Control-Allow-Origin to a single resource under a web site or in an entire domain

Access-control-allow-origin: http://example.com access-control-allow-credentials: true (Optional)

Will allow any domain to submit a request to you

Access-control-allow-origin: * access-control-allow-credentials: true (optional)

Submit a cross-domain request

If CORS is enabled on the server side, submitting a cross-domain request is no different than a normal XMLHttpRequest request. For example, now example.com can submit a request to www.example2.com.

var xhr = new XMLHttpRequest(); // xhr.withCredentials = true; / / if you need a Cookie XHR. Open (' GET 'and' http://www.example2.com/hello.json '); xhr.onload = function(e) { var data = JSON.parse(this.response); . } xhr.send();

Server Nginx configuration

To implement CORS across domains, the server needs a process like the one shown below

  • For simple requests, such as GET, simply add access-Control-Allow-Origin after HTTP Response.
  • For non-simple requests, such as POST, PUT, and DELETE, the browser responds twice. The first preflight (method: OPTIONS) verifies that the source is valid and returns allowed headers, etc. The second is the real HTTP reply. So the server must process the OPTIONS reply.

The process is as follows

  • First check whether the HTTP header has the Origin field.
  • If not, or not allowed, directly as a normal request processing, end;
  • Preflight (method=OPTIONS);
  • Allow-headers, allow-methods, etc.
  • If it is not preflight, allow-Origin, allow-credentials, and so on are returned, and normal contents are returned.

In pseudocode

Location /pub/(.+) {if ($http_origin ~ < allowed field (regular match) >) {add_header 'access-control-allow-origin' "$http_origin"; add_header 'Access-Control-Allow-Credentials' "true"; if ($request_method = "OPTIONS") { add_header 'Access-Control-Max-Age' 86400; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE'; add_header 'Access-Control-Allow-Headers' 'reqid, nid, host, x-real-ip, x-forwarded-ip, event-type, event-id, accept, content-type'; add_header 'Content-Length' 0; add_header 'Content-Type' 'text/plain, charset=utf-8'; return 204; }} # Normal nginx configuration...... }

Nginx configuration example

Example 1: Allow the application example.com to extract data across domains on www.example2.com

Find the server entry in nginx.conf and add the following configuration

location /{ add_header 'Access-Control-Allow-Origin' 'http://example.com'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With'; add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS'; . }

If you need to allow access from any domain, you can configure it this way

add_header Access-Control-Allow-Origin *;

Note the following

The first directive: Authorize requests from example.com (required) The second directive: when the flag is true, respond to whether the request can be exposed (optional) the third directive: Return headers that allow script access (optional) The fourth directive: Specify the request method, which can be GET, POST, OPTIONS, PUT, DELETE, etc. (optional)

Restart the Nginx

$ service nginx reload

Test cross-domain requests

$ curl -I -X OPTIONS -H "Origin: http://example.com" http://www.example2.com

On success, the response header looks like the following

HTTP/1.1 200 OK Server: nginx Access-Control-Allow-Origin: example.com

Example 2: Nginx allows multiple domain names to be accessed across domains

Because the access-Control-allow-origin parameter allows only one domain name or *, you can use the following methods to Allow cross-domain Access of multiple domain names.

  • Methods a

To Allow users to request Access to www.example2.com domain names from www.example.com, m.example.com, or wap.example.com, return the access-Control-allow-origin header

In nginx.conf, locate the server entry and add the following configuration

map $http_origin $corsHost { default 0; "~http://www.example.com" http://www.example.com; "~http://m.example.com" http://m.example.com; "~http://wap.example.com" http://wap.example.com; } server { listen 80; server_name www.example2.com; root /usr/share/nginx/html; location / { add_header Access-Control-Allow-Origin $corsHost; }}

  • Method 2

To Allow users to request requests from localhost, www.example.com, or m.example.com to Access the xxx.example2.com domain name, return the access-control-allow-origin header

In the Nginx configuration file, xxx.example2.com domain name location /

set $cors ''; if ($http_origin ~* 'https? ://(localhost|www\.example\.com|m\.example\.com)') { set $cors 'true'; } if ($cors = 'true') { add_header 'Access-Control-Allow-Origin' "$http_origin"; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requ ested-With'; } if ($request_method = 'OPTIONS') { return 204; }

  • Methods three

To Allow user requests from *. Example.com to Access xxx.example2.com, return the access-control-allow-origin header

In the Nginx configuration file, xxx.example2.com domain name location /

if ( $http_origin ~ http://(.*).example.com){ set $allow_url $http_origin; } #CORS(Cross Orign resource-sharing) configure whether to Allow requests with authentication information add_header access-control-allow-credentials true; Add_header access-Control-allow-origin $allow_url; add_header access-control-allow-origin $allow_url Add_header access-control-allow-headers 'x-requested-with,content-type,Cache-Control,Pragma,Date,x-timestamp'; # allows you to use the request method, by commas add_header Access - Control - Allow - the Methods' POST, GET, OPTIONS, PUT, DELETE '; Add_header access-Control-expose-headers' www-authenticate, server-authorization '; Add_header P3P 'policyref="/w3c/p3p. XML ", CP="NOI DSP PSAa OUR BUS IND ONL UNI COM NAV INT LOC"';

  • Methods four

To Allow users to request Access from xxx1.example.com or xxx1.example1.com. Example2.com, return the access-control-allow-origin header

In the Nginx configuration file, xxx.example2.com domain name location /

location / { if ( $http_origin ~ .*.(example|example1).com ) { add_header Access-Control-Allow-Origin $http_origin; }}

Example 3: Nginx cross-domain configuration and support for DELETE,PUT requests

By default, access-Control-allow-origin supports only GET, HEAD, POST, and OPTIONS requests. When DELETE is used to initiate a cross-domain request, the browser initiates the OPTIONS request first for security reasons. The request received by the server changes to OPTIONS, causing 405 Method Not Allowed on the server.

The solution

The OPTIONS request is processed first

if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; # other header information configuration, omit... return 204; }

If the request type is OPTIONS, set the Allow header and reprocess the request. The first request is an OPTIONS request and the second is a DELETE request.

Add_header access-control-allow-origin; add_header access-control-allow-origin; location / { if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; return 204; } index index.php; try_files $uri @rewriteapp; }

Example 4: More configuration examples

  • The sample a

The following Nginx configuration enables CORS, with support for preflight requests. # # Wide-open CORS config for nginx # location / {     if ($request_method = 'OPTIONS') {        add_header 'Access-Control-Allow-Origin' '*';        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';        #        # Custom headers and headers various browsers *should* be OK with but aren't        #        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';        #        # Tell client that this pre-flight info is valid for 20 days        #        add_header 'Access-Control-Max-Age' 1728000;        add_header 'Content-Type' 'text/plain charset=UTF-8';        add_header 'Content-Length' 0;        return 204;     }     if ($request_method = 'POST') {        add_header 'Access-Control-Allow-Origin' '*';        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';     }     if ($request_method = 'GET') {        add_header 'Access-Control-Allow-Origin' '*';        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';     } }

  • Example 2

if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' 'https://docs.domain.com'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, 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,Authorization,tok en'; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' 'https://docs.domain.com'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, 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,Authorization,tok en'; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' 'https://docs.domain.com'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, 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,Authorization,tok en'; }

Other skills

Add the following statement to the HTTPD configuration or. Htaccess file

SetEnvIf Origin "^(.*\.example\.com)$" ORIGIN_SUB_DOMAIN=$1   Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN

By setting the access-Control-Allow-Origin response header on the server

  • Allow access from all sources

<? php header("Access-Control-Allow-Origin: *"); ? >

  • Allow access from a specific source

<? php header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']); ? >

  • Configure multiple access sources

Since the browser implementation only supports a single origin, *, and NULL, if you want to configure multiple access sources, you can handle the following in the code

<? php $allowed_origins = array( "http://www.example.com" , "http://app.example.com" , "http://cms.example.com" , ); if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)){ @header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']); }? >

CORS is enabled in HTML

<meta http-equiv="Access-Control-Allow-Origin" content="*">

www.google.com

http://t.cn/RZEYPmD

http://t.cn/RhcAN2d

The to – u.x yz / 2016/06/30 /… Coderq. Making. IO / 2016/05/13 /…

Author: Mike

Source: The beauty of operation and maintenance

 

Recommended reading

Nginx vs. HTTPD

Nginx uses proxy reverse proxy to solve Ajax cross-domain access, the browser does not show the link after the jump