为什么 Referrer-Policy 如此重要?
在当今的互联网环境中,隐私和安全成为开发者和用户最关心的问题之一。Referrer-Policy 是一个关键的 HTTP 头,它控制着浏览器如何处理引荐来源信息(Referrer),直接影响数据泄露的风险和用户体验。
通过合理设置 Referrer-Policy,您可以:
防止敏感信息通过 URL 泄露
控制第三方网站获取您的流量来源数据
提升用户隐私保护水平
满足 GDPR 等隐私法规的要求
在 Node.js 服务端设置 Referrer-Policy
使用 Node.js 的 Express 框架时,设置 Referrer-Policy 非常简单。以下是完整示例代码:
const express = require('express');
const app = express();
// 设置 Referrer-Policy 中间件
app.use((req, res, next) => {
res.setHeader(‘Referrer-Policy’, ‘strict-origin-when-cross-origin’);
next();
});
// 路由示例
app.get(’/’, (req, res) => {
res.send(‘首页’);
});
app.listen(3000, () => {
console.log(‘服务器已启动’);
});
常见 Referrer-Policy 值及其含义:
- no-referrer: 完全不发送 Referrer 信息
- no-referrer-when-downgrade: 默认值,HTTPS→HTTPS 发送完整 URL,HTTPS→HTTP 不发送
- same-origin: 仅在同源请求时发送
- strict-origin: 只发送源信息,且仅当安全等级不降低时
- strict-origin-when-cross-origin: 跨域时使用 strict-origin,同源发送完整 URL
浏览器端 Fetch API 的 Referrer-Policy 设置
在使用浏览器 Fetch API 时,您可以通过多种方式控制 Referrer 行为:
方法一:全局设置 meta 标签
<meta name="referrer" content="strict-origin-when-cross-origin">
方法二:单个 fetch 请求设置
fetch('https://api.example.com/data', {
referrerPolicy: 'no-referrer-when-downgrade',
// 其他请求选项...
})
.then(response => response.json())
.then(data => console.log(data));
浏览器支持的 referrerPolicy 选项与 HTTP 头略有不同,包括:
- no-referrer
- no-referrer-when-downgrade
- same-origin
- origin
- strict-origin
- origin-when-cross-origin
- strict-origin-when-cross-origin
- unsafe-url
最佳实践与常见问题
在实际应用中,我们推荐以下策略:
- 默认使用 strict-origin-when-cross-origin 策略
- 敏感页面使用 no-referrer 或 same-origin
- 测试不同策略对您网站功能的影响
- 监控引用数据确保符合预期
常见问题解答:
Q: 设置 Referrer-Policy 会影响 SEO 吗? A: 大多数搜索引擎爬虫会忽略 Referrer-Policy,但建议保留适当策略以便分析流量来源。
Q: 如何测试我的 Referrer-Policy 是否生效? A: 可以使用 Chrome DevTools 的 Network 面板查看请求头,或使用在线测试工具。
Q: 多个设置冲突时哪个优先? A: 优先级顺序为:单个请求设置 > 页面 meta 标签 > 服务器 HTTP 头。