你如何在页面加载时重定向用户,同时仍然让推特卡工作



我正在将Twitter卡集成到我的网站中,特别是应用程序安装和深度链接功能。为此,我在html页面的标题部分添加了所需的元标记。

我的应用程序中发布到推特的功能可以分享其他网站的文章。为了共享一个不在我的域上但仍然显示推特卡的网站url,我制作了一个简单的短url,发布在推特上,指向带有元标签的html页面,然后将用户重定向到原始网站,但我没有得到想要的结果。

首先,我尝试通过在标头中返回301响应代码来重定向用户。这会按照我的意愿重定向用户(将我的重定向页面排除在浏览器历史记录之外),但推特不会拾取元标签,因此卡不会显示。

接下来,我尝试在Twitter卡元标签下面使用一个元标签,如下所示:

<META http-equiv="refresh" content="0;URL=http://www.mywebsite.com">

使用这种方法,Twitter卡会正确显示,但现在浏览器中启用了后退按钮。此外,我读到不建议使用这种方法,因为出于安全原因,搜索引擎倾向于从结果中删除这样做的网站。

有人知道如何在不启用浏览器中的后退按钮的情况下重定向用户,并且仍然允许评估元标签吗?我更喜欢一种不使用Javascript的方法。

我发现了一个有趣的方法来解决这个问题。

我只需要推特元标签可用时,推特是一个看我的网站。因此,当用户或机器人向我的网站提出请求时(Twitter必须这样做才能从元标签中填充卡片信息),我会检查提出请求的用户代理。如果它是一个Twitter机器人(它的用户代理目前是Twitterbot/1.0),那么我会在标题中返回一个200响应代码和一个元标签重定向的页面(以防万一)。否则,我会返回一个302响应代码,浏览器会立即将我的使用重定向到那里。

这绕过了后退按钮问题和搜索引擎不喜欢我的元标签重定向网站的问题(因为机器人永远不会看到它们!)。

更新

我最近有人问我如何做到这一点的更多细节,所以我想我会提供一个例子。我在服务器上使用C#,但代码很容易判断你是否使用了不同的语言。

/// <summary>
/// Redirects a user to the location related to the given id.
/// </summary>
/// <param name="id"></param>
public ActionResult Index(Int32 id)
{
// Retrieve details about the short link id passed in
using (DataEntities context = new DataEntities())
{
ShortLink shortLink = context.ShortLinks.Single(s => s.Id == id);
// If the user agent is a twitter bot (currently Twitterbot/1.0), return the page with a meta redirect (just in case) so Twitter can still read the meta tags.
if (Request.UserAgent.ToString().ToLower().Contains("twitterbot"))
{
TwitterCardModel model = new TwitterCardModel
{
Id = id,
Site = "@YOUR_TWITTER_HANDLE",
Title = shortLink.Title,
Description = shortLink.Description,
RedirectUrl = shortLink.FullUrl,
ImageUrl = shortLink.ImageUrl
};
return View(model);
}
// Otherwise, redirect the user to the original page.
Response.Redirect(shortLink.FullUrl, true);
return null;
}
}

如果请求来自twitter机器人,这就是我返回的HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
@* Twitter cards *@
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@Model.Site">
<meta name="twitter:title" content="@Model.Title" />
<meta name="twitter:description" content="@Model.Description" />
@if (!String.IsNullOrEmpty(Model.ImageUrl))
{
<meta name="twitter:image" content="@Model.ImageUrl">
}
<meta name="twitter:app:name:iphone" content="YOUR APP NAME"/>
<meta name="twitter:app:id:iphone" content="YOUR APPLE APP ID"/>
<meta name="twitter:app:url:iphone" content="YOUR DEEP LINK TO YOUR CONTENT IN YOUR APP"/>
@* Handle page redirect to the full article *@
<meta http-equiv="refresh" content="0;URL=@Model.RedirectUrl">
<title></title>
</head>
<body>
</body>

最新更新