APISIX CORS Configuration Guide

APISIX CORS Configuration Overview
Introduction to CORS
Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that restricts cross-origin HTTP requests. APISIX provides comprehensive CORS support to manage these restrictions safely.
Basic CORS Configuration
Enable CORS
curl http://127.0.0.1:9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"uri": "/api/*",
"plugins": {
"cors": {
"allow_origins": "*",
"allow_methods": "GET,POST,PUT,DELETE",
"allow_headers": "Content-Type,Authorization",
"expose_headers": "X-Custom-Header",
"max_age": 3600
}
}
}'
Advanced CORS Settings
Specific Origin Configuration
curl http://127.0.0.1:9080/apisix/admin/routes/2 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"uri": "/secure/*",
"plugins": {
"cors": {
"allow_origins": "https://example.com,https://api.example.com",
"allow_methods": "GET,POST",
"allow_headers": "Content-Type,Authorization,X-Requested-With",
"expose_headers": "X-Custom-Header",
"max_age": 3600,
"allow_credential": true
}
}
}'
Security Note: Avoid using
allow_origins: "*"
in production environments. Always specify exact origins for better security.
Handling Preflight Requests
OPTIONS Request Configuration
curl http://127.0.0.1:9080/apisix/admin/routes/3 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"uri": "/api/*",
"plugins": {
"cors": {
"allow_origins": "https://example.com",
"allow_methods": "GET,POST,PUT,DELETE,PATCH,OPTIONS",
"allow_headers": "*",
"max_age": 3600,
"allow_credential": true,
"expose_headers": "X-Request-Id"
}
}
}'
Best Practices
Security Recommendations
- Specify exact origins instead of wildcards
- Limit allowed methods to only those needed
- Set appropriate max age for preflight caching
- Be cautious with credentials handling
- Regularly audit CORS configurations