Nginx can also set up CORS in addition to reverse proxy to resolve cross-domain

Build a cross-domain environment

Open the local host file and configure a new domain name to build a cross-domain environment. Add a line 127.0.0.1 dazhihui.com

Create a new folder in the nginx directory as the actual resource address that our new domain name points to

Path:/usr/local/etc/nginx/html/dazhihui, create a new oneindex.htmlFile, the content can be customized

在 conf.dFile and then create a new filecors.conf, write the following configuration

Server {# listen 80; Server_name dazhihui.com; # the location based on the access path configuration / {root/usr/local/etc/nginx/HTML/dazhihui; index index.html; }}Copy the code

Save and restart nginx

We request dazhihui.com to see if we can access it

If this screen is displayed, the first step is successfully configured

Configure CORS to resolve cross-domain issues

We have changed the requested address for the local files in the previous section to the new address dazhihui.com

Refresh the browser and you can see that a cross-domain problem has occurred due to a different host

Modify thecors.conf, write the following configuration

Server {# listen 80; Server_name dazhihui.com; Location / {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' $http_access_control_request_headers; * add_header 'access-control-expose-headers'' content-length, content-range '; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Max-Age' 1728000; Add_header 'content-type' 'text/plain '; charset=utf-8'; add_header 'Content-Length' 0; return 204; # 200 can also} root/usr/local/etc/nginx/HTML/dazhihui; index index.html; }}Copy the code

Restart Nginx and refresh the browser

You can see that the cross-domain problem has disappeared and the content has returned normally