๐ API KEY AUTHENTICATION IN NGINX REVERSE PROXY (END-TO-END)¶
API keys are commonly used for:
-
Protecting internal APIs
-
Allowing only specific clients to access an API
-
Blocking unauthorized calls
-
Securing microservices
NGINX can check API keys before forwarding the request to your backend.
๐ฅ 1. How API Key Authentication Works¶
Client โ NGINX Reverse Proxy โ Backend Server
NGINX checks:
- Header: X-API-KEY
- or Query: ?api_key=
If key is valid โ request is forwarded.
If key is invalid โ 401 Unauthorized.
๐งฑ 2. Create a Secret API Key¶
Example:
You will verify this in NGINX.
โ๏ธ 3. Reverse Proxy with API Key Authentication¶
Create or edit your config:
Paste this:
server {
listen 80;
server_name example.com;
# Expected API key
set $api_key "my-super-secret-key-123";
location / {
# Extract API key from header
set $client_key $http_x_api_key;
# If header is empty, check query ?api_key=
if ($client_key = "") {
set $client_key $arg_api_key;
}
# Validate
if ($client_key != $api_key) {
return 401;
}
# Forward request to backend
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
๐งช 4. Test the API Key¶
โ Without API Key:¶
Response:
โ With API Key (Header):¶
โ With API Key (Query):¶
๐ 5. Hide API Key in Separate File (More Secure)¶
Store the key in its own file:
Add:
Protect the file:
Then include it:
๐ก 6. Allow Only Specific Endpoints to Require API Key¶
Example: Protect /admin but not /public.
location /admin/ {
if ($http_x_api_key != "my-super-secret-key-123") {
return 401;
}
proxy_pass http://127.0.0.1:3000;
}
location /public/ {
proxy_pass http://127.0.0.1:3000;
}
๐ 7. Return JSON Instead of Plain 401¶
Add proper headers:
โก 8. Reject Requests Missing API Key (No Proxy)¶
This saves backend resources.
๐งฐ 9. Advanced Method โ Using Map (Cleaner, No โifโ inside location)¶
map $http_x_api_key $key_ok {
default 0;
"my-super-secret-key-123" 1;
}
server {
listen 80;
location / {
if ($key_ok = 0) { return 401; }
proxy_pass http://127.0.0.1:3000;
}
}
๐ก 10. API Key Rotation (Multiple Keys Support)¶
Supports multiple clients.
๐ DONE! API Key Authentication Added to Reverse Proxy¶
You now have:
โ API Key verification
โ Header + query param support
โ Secure key storage
โ JSON error response
โ Multiple keys
โ Key rotation
โ Endpoint-based protection