การแชร์ทรัพยากรข้ามต้นทาง (CORS)
ใช้นโยบาย CORS ใน Nginx เพื่อเปิดใช้งานคำขอข้ามโดเมนที่ปลอดภัยสำหรับ API ของคุณ
การแชร์ทรัพยากรข้ามต้นทาง (CORS) เป็นบทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is CORS?
Imagine you're building a web application. Your frontend (like a React app) runs on app.example.com, but it needs to fetch data from your API running on api.example.com.
This is where Cross-Origin Resource Sharing (CORS) comes in. It's a security feature implemented by web browsers to control how web pages from one origin can request resources from another origin.
The Same-Origin Policy
CORS is a relaxation of the browser's Same-Origin Policy. This policy is a critical security mechanism that prevents a malicious website from reading sensitive data from another site.
- Origin is defined by the protocol, host, and port.
https://app.example.com:443is different fromhttp://app.example.com:80orhttps://api.example.com:443.
Without CORS, browsers would block your frontend from talking to your API because they have different origins.
How CORS Works
When your browser detects a cross-origin request, it adds an Origin header to the request. The server then needs to respond with specific CORS headers to tell the browser it's allowed.
The most important header is Access-Control-Allow-Origin. If this header is present in the server's response and its value matches the client's origin (or is *), the browser allows the request.
Simple vs. Preflight Requests
CORS requests can be categorized into two types:
- Simple Requests: These are direct GET, HEAD, or POST requests with specific content types (like
text/plain). The browser sends them immediately, expecting CORS headers in the response. - Preflight Requests: For more complex requests (e.g., PUT, DELETE, custom headers, or specific content types), the browser first sends an
OPTIONSrequest. This 'preflight' checks with the server if the actual request is safe to send.
Nginx for CORS Headers
Since Nginx often acts as a reverse proxy or API gateway, it's the perfect place to manage CORS headers for your backend services. We can use Nginx directives to add the necessary Access-Control-* headers to responses.
The primary directive for this is add_header, which allows us to inject custom HTTP headers into Nginx responses.
Configuring Allow-Origin
Let's configure Nginx to allow requests from a specific origin, https://app.example.com, to your API.
We'll add the Access-Control-Allow-Origin header within a location block that handles your API requests.
server {
listen 80;
server_name api.example.com;
location /api/ {
add_header 'Access-Control-Allow-Origin' 'https://app.example.com';
proxy_pass http://backend_api_service;
}
}Handling Multiple Origins
What if you have multiple frontends that need to access your API? You can't list multiple origins in Access-Control-Allow-Origin directly. Instead, you can use Nginx's map directive to dynamically set the header based on the incoming Origin header.
http {
map $http_origin $cors_origin {
default "";
"https://app.example.com" "https://app.example.com";
"https://dev.example.com" "https://dev.example.com";
}
server {
listen 80;
server_name api.example.com;
location /api/ {
if ($cors_origin ~ ".") {
add_header 'Access-Control-Allow-Origin' $cors_origin;
}
proxy_pass http://backend_api_service;
}
}
}Configuring Preflight Requests
For preflight (OPTIONS) requests, the browser expects specific headers in response to its OPTIONS call. Nginx needs to intercept these requests and respond with the appropriate CORS headers, often without proxying to the backend.
server {
listen 80;
server_name api.example.com;
location /api/ {
# Handle preflight OPTIONS requests
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'https://app.example.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
# For actual requests
add_header 'Access-Control-Allow-Origin' 'https://app.example.com';
proxy_pass http://backend_api_service;
}
}Essential CORS Headers
Beyond Access-Control-Allow-Origin, these headers are crucial for full CORS support:
Access-Control-Allow-Methods: Specifies allowed HTTP methods (e.g.,GET, POST, PUT).Access-Control-Allow-Headers: Lists headers the client is allowed to send (e.g.,Content-Type, Authorization).Access-Control-Allow-Credentials: Set totrueif the client can send cookies or HTTP authentication.Access-Control-Max-Age: How long the preflight response can be cached by the browser (in seconds).
Comprehensive CORS Setup
Here's a more complete Nginx configuration snippet that handles both simple and preflight CORS requests, allowing a specific origin to interact with your API, including sending credentials.
server {
listen 80;
server_name api.example.com;
location /api/ {
set $cors_origin "https://app.example.com"; # Or use map directive
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' "$cors_origin";
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
add_header 'Access-Control-Allow-Origin' "$cors_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' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
proxy_pass http://backend_api_service;
}
}CORS Header Check
Which of the following headers are essential for Nginx to respond correctly to a CORS preflight (OPTIONS) request?
Recap: Nginx CORS
In this lesson, you learned about Cross-Origin Resource Sharing (CORS) and why it's vital for secure web applications. We covered:
- The Same-Origin Policy and why CORS exists.
- The difference between simple and preflight requests.
- How to configure Nginx using
add_headerandmapdirectives to manage CORS. - Key CORS headers like
Access-Control-Allow-Origin,Access-Control-Allow-Methods,Access-Control-Allow-Headers, andAccess-Control-Max-Age.
Properly configuring CORS in Nginx ensures your frontend applications can securely communicate with your backend APIs across different domains.
เรียนรู้ API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 12
- บทเรียน
- 48
คำถามที่พบบ่อย
บทเรียน “การแชร์ทรัพยากรข้ามต้นทาง (CORS)” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การแชร์ทรัพยากรข้ามต้นทาง (CORS)” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การแชร์ทรัพยากรข้ามต้นทาง (CORS)”
ใช้นโยบาย CORS ใน Nginx เพื่อเปิดใช้งานคำขอข้ามโดเมนที่ปลอดภัยสำหรับ API ของคุณ คุณปฏิบัติ API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การแชร์ทรัพยากรข้ามต้นทาง (CORS)” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) นี้ได้ไหม
ได้ บทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การกำหนดเวอร์ชัน API ด้วย Nginx
- การแชร์ทรัพยากรข้ามต้นทาง (CORS)
- การจำกัดอัตราและการควบคุมปริมาณด้วย Nginx
- การกำหนดเส้นทางไปยังไมโครเซอร์วิสตามพาธ