Cross-Origin Resource Sharing Control
Browsers restrict cross-origin requests to prevent security vulnerabilities like CSRF attacks. When a malicious website attempts to make requests to your domain on behalf of users, proper CORS configuration becomes essential.
Nginx CORS Configuration
The `add_header` directive manages response headers for CORS:
- Syntax:
add_header name value [always];
- Default: —
- Context: http, server, location, if in location
Parameters:
name: The response header field name
value: The corresponding header value
CORS Implementation Example
location ~ \.(html|htm)$ {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
root /var/www/html;
}
Anti-Hotlinking Protection
Hotlinking protection prevents unauthorized websites from embedding your resources, which conserves bandwidth and prevents content theft.
Referer-Based Protection Module
The
ngx_http_referer_module blocks requests with invalid Referer headers.
Basic Configuration Example
valid_referers none blocked server_names
*.trustedsite.com trustedsite.*
~\.google\.;
if ($invalid_referer) {
return 403;
}
Referer Hash Configuration
referer_hash_bucket_size
- Syntax:
referer_hash_bucket_size size;
- Default: 64
- Context: server, location
- Sets the bucket size for the valid referers hash table
referer_hash_max_size
- Syntax:
referer_hash_max_size size;
- Default: 2048
- Context: server, location
- Defines the maximum size of the valid referers hash table
valid_referers Directive
- Syntax:
valid_referers none | blocked | server_names | string ...;
- Default: —
- Context: server, location
Options:
none: Allows requests with missing Referer header
blocked: Allows requests where Referer is masked by firewall/proxy (doesn't start with http:// or https://)
server_names: Allows requests with server name in Referer
string: Defines allowed server names with optional URI prefix. Wildcards (*) permitted at start/end
Anti-Hotlinking Implementation Example
Create test file
/var/www/html/test_link.html:
<html>
<head>
<meta charset="utf-8">
<title>Resource Link Test</title>
</head>
<body>
<h1>Test Page</h1>
<img src="http://192.168.1.100/resource.jpg"/>
</body>
</html>
Configure Nginx to restrict access:
location ~ \.(jpg|gif|png)$ {
valid_referers none blocked www.mydomain.com *.mydomain.com;
if ($invalid_referer) {
return 403;
}
root /var/www/images;
}
location /test_link.html {
root /var/www/html;
}
Access will be denied when embedded from unauthorized domains while allowing direct access from permitted sources.