1. Understand CORS and homologous policies
1.1 Same Origin Policy
Same-origin policy is a browser security mechanism used to prevent web applications from accessing data from different sources (different domain names, protocols, or ports). It ensures the isolation of web applications and prevents malicious websites from accessing user data or performing unsafe operations.
Under the same origin policy, resources within the same domain (same protocol, domain name, and port) can be accessed freely. But if the protocol, domain name, or port is any different, the browser will block this access.
1.2 Cross-domain resource sharing (CORS)
CORS (Cross-Origin Resource Sharing) is a W3C standard used to solve cross-domain access problems. Through CORS, the server can declare which sources of requests are allowed, and which HTTP methods and headers are allowed to access the client.
The implementation of CORS relies on specific HTTP headers returned by the server that guides the browser to allow or deny specific cross-domain requests.
2. The basic principles of Nginx to solve cross-domain problems
Nginx can support CORS by configuring HTTP response headers. These headers include Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Credentials, etc. By configuring these headers in Nginx, specific domains, methods, and headers can be allowed to cross-domain access.
3. Configure Nginx to solve cross-domain problems
Here are the specific steps on how to configure CORS in Nginx.
3.1 Basic configuration
Suppose we have an API server with the domain name , and we need to allow cross-domain requests from the front-end application.
First, find or create an Nginx configuration file (usually located in the /etc/nginx/ or /etc/nginx// directory), and then add CORS-related header configurations to the server block (server block) or location block (location block) that needs to be cross-domain.
server { listen 80; server_name ; location / { # Set a domain name that allows cross-domain, and you can use the wildcard character '*' to allow all domains to access. add_header 'Access-Control-Allow-Origin' ''; # Set the allowed HTTP methods add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT'; # Set the allowed request header add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type, Accept, Origin, X-Requested-With'; # If you need to support cookies, you can set the following header add_header 'Access-Control-Allow-Credentials' 'true'; # If it is a preflight request (OPTIONS request), it will directly return the 204 status code if ($request_method = 'OPTIONS') { return 204; } # The processing logic of other normal requests proxy_pass http://backend_server; } }
3.2 Detailed explanation of key configuration items
Access-Control-Allow-Origin: Specifies the source that allows cross-domain requests. Can be set to a specific domain name (such as ), or use wildcard * to allow all sources. When using wildcards, Access-Control-Allow-Credentials is not allowed to be set to true.
Access-Control-Allow-Methods: Specifies the allowed HTTP request methods, such as GET, POST, OPTIONS, PUT, DELETE, etc. It can be set according to actual needs.
Access-Control-Allow-Headers: Specifies custom HTTP headers that are allowed to send by clients, such as Authorization, Content-Type, etc. This configuration item is often used to support complex requests (requests with custom headers).
Access-Control-Allow-Credentials: This option must be set to true if the client requests include credentials (such as cookies). Note that Access-Control-Allow-Origin cannot be * at this time, it must be a specific domain name.
Processing of pre-flight requests: Before sending some complex requests, the browser will send an OPTIONS request for pre-flight and ask the server whether to allow the request. Nginx can directly return status code 204 when an OPTIONS request is detected, indicating that the request is allowed, but does not contain anything.
3.3 Configuring wildcards
In some scenarios, if you need to allow all domain access (i.e., not restrict the source of cross-domain requests), you can set Access-Control-Allow-Origin to *:
add_header 'Access-Control-Allow-Origin' '*';
It should be noted that when using wildcards, Access-Control-Allow-Credentials cannot be enabled at the same time, otherwise the browser will reject the request.
3.4 Dynamically set CORS header
If you need to dynamically set Access-Control-Allow-Origin based on request, you can use the $http_origin variable to match the request source. For example:
location / { if ($http_origin ~* 'https?://(www.)?(|)') { 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' 'Authorization, Content-Type, Accept'; } if ($request_method = 'OPTIONS') { return 204; } proxy_pass http://backend_server; }
This configuration can dynamically allow multiple domain names to be accessed across domains when specific conditions are met.
4. Processing of preflight requests and OPTIONS methods
A preflight request is a mechanism defined in the CORS specification to detect whether the server allows a certain cross-domain request before the actual request. When the browser sends some complex requests, it will first send an OPTIONS request, asking the server whether to allow the request.
Nginx can handle such preflight requests through simple configuration:
if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE'; add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type, Accept, Origin, X-Requested-With'; return 204; }
This configuration returns a 204 No Content response when an OPTIONS request is received, with the necessary CORS header information indicating that the server allows the actual request next.
5. Things to note in practice
5.1 Security considerations
Although CORS is an effective means of solving cross-domain problems, all domain access should not be allowed at will (i.e., set Access-Control-Allow-Origin to *). This configuration may cause security risks, as any script from any source can access resources. Therefore, the allowed sources should be clearly specified during configuration and the permissions for cross-domain access should be strictly controlled.
5.2 Performance optimization
CORS request processing increases the load on the server, especially when preflight requests are frequent. To reduce performance overhead, optimization can be performed by:
Enable caching: By setting the Access-Control-Max-Age header, the browser can cache the results of preflight requests, reducing the number of preflights before the actual request.
Merge requests: When possible, reduce the number of cross-domain requests and avoid unnecessary preflight requests.
5.3 Configuration Management
When managing Nginx configurations in a production environment, it is recommended to manage CORS-related configurations separately from other configurations. For example, you can create a separate file in Nginx's configuration file to manage CORS configuration and include this file in the required server or location block:
include /etc/nginx/;
This way can make the configuration clearer and easier to manage.
6. Sample Scenarios and Configuration Examples
6.1 Single-page application and API backend
Suppose there is a single page application (SPA) deployed in which it fetches data from Ajax requests. The configuration of Nginx can be as follows:
server { listen 80; server_name ; location /api/ { add_header 'Access-Control-Allow-Origin' ''; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type'; if ($request_method = 'OPTIONS') { return 204; } proxy_pass http://backend_api_server; } }
6.2 Support cross-domain access of multiple domain names
If you need to support cross-domain requests from multiple domain names, such as and , you can use the following configuration:
location /api/ { if ($http_origin ~* 'https?://(|)') { 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' 'Authorization, Content-Type'; } if ($request_method = 'OPTIONS') { return 204; } proxy_pass http://backend_api_server; }
7. Summary
Configuring CORS header information through Nginx can effectively solve the front-end cross-domain problem, allowing front-end applications to request resources from different domain names, protocols, or ports. During the configuration process, the ease of use of security, performance optimization, and management need to be carefully considered to ensure the secure and efficient handling of cross-domain requests. Nginx's powerful configuration capabilities allow it to flexibly respond to various cross-domain needs and provide strong support for front-end applications.
The above is the detailed content of using Nginx to solve front-end cross-domain problems. For more information about Nginx to solve front-end cross-domain, please pay attention to my other related articles!