搭建图片API时,如何获取浏览器img请求的来源域名?
Great question—this is a super common pain point when building image delivery APIs, since img src requests don’t trigger CORS preflights or send the Origin header like XHR/fetch calls do. Here are the most reliable approaches to capture the requesting domain:
1. Use the Referer HTTP Header
This is the go-to method for most cases. When a browser loads an image via an <img> tag embedded in a web page, it typically sends a Referer header containing the full URL of the page that’s loading the image. Your server can parse this URL to extract the hostname (the requesting domain).
For example, in Node.js with Express, you’d do something like:
app.get('/random', (req, res) => { let requestingDomain = 'Unknown'; if (req.headers.referer) { try { const refererUrl = new URL(req.headers.referer); requestingDomain = refererUrl.hostname; } catch (err) { // Handle invalid or malformed Referer URL } } // Log requestingDomain to your server records // Serve your image file... });
Caveats to keep in mind:
- Some users or browsers have strict privacy settings (like "Do Not Track" or restrictive referrer policies) that will omit the
Refererheader entirely. - If the image is loaded directly in the browser’s address bar (not embedded in a page), there won’t be a
Referervalue. - Browsers may strip the
Refererif the embedding page uses HTTPS but your API uses HTTP (mixed content), or if the page’s referrer policy is set tono-referrer.
2. Require a Signed/Tokenized Request (For Maximum Reliability)
If you need guaranteed domain tracking (and don’t mind asking your API users to make a small change), you can require them to include a domain parameter in the image URL—along with a signature to prevent tampering.
For example, your users would embed images like this:
<img src="myapi.com/random?domain=example.com&signature=abc123xyz..." />
Your server would then:
- Verify the signature matches the
domainparameter (using a shared secret key you provide to your API users). - Log the verified
domainvalue.
This method eliminates reliance on browser headers and gives you full control over the data you receive, but it requires coordination with every site using your API.
3. Service Worker Interception (Advanced, Site-Dependent)
If your API users are willing to add code to their sites, they can register a Service Worker that intercepts outgoing image requests to your API and adds a custom header (like X-Requesting-Domain) with their domain.
However, this is a heavy lift for most users, so it’s only practical if you’re working with a small, trusted set of sites using your API.
Final Recommendation
Start with the Referer header—it’s the easiest and most widely compatible method. For cases where Referer is missing, you can fall back to logging "Unknown" or offer the signed request option to users who need more reliable tracking.
内容的提问来源于stack exchange,提问作者Jauny

