【问题标题】:Nginx config for serving snapshots to the Google bot用于向 Google bot 提供快照的 Nginx 配置
【发布时间】:2013-07-01 08:56:17
【问题描述】:

我有一个 AngularJS 应用程序,我想在 Google 上正确编入索引。

我编写了一个客户端,它会抓取网站的链接,然后使用 Phantomjs 制作快照下载页面。这一切都很好。我遇到的问题是将这些快照提供给 Google 机器人。

出于某种原因,Google 机器人将?_escaped_fragment= 附加到我的网址中。例如,http://me.com/about 更改为 http://me.com/about?_escaped_fragment=。我已经在访问日志中验证了这一点。

我正在尝试捕获此请求并使用此配置为 Google bot 提供快照:

location / {
    if ($args ~ "_escaped_fragment_=") {
        rewrite ^ /snapshots/$1;
    }
}

但是,请求此 URL:http://me.com/about?_escaped_fragment= 始终会导致 404。与其他页面相同。

快照存储在/snapshots,相对于网站的根目录。它们以它们的页面命名,遵循目录结构,因此http://me.com/business/register/snapshots/business/register.html 中有一个快照。

我该怎么做才能让这些快照正常工作?

谢谢。

【问题讨论】:

    标签: angularjs nginx snapshot


    【解决方案1】:

    好的,首先让我解释一下为什么google使用?_escaped_fragment_,这用于依赖ajax的网站,并用哈希标记他们的页面,例如如果你有http://example.com/gallery/#!image1并且每次用户更改为下一个图像您将哈希更新为image2image3,但如果用户直接转到http://example.com/gallery/#!image50,您的javascript使用该哈希直接加载第50张图像而不是image1(服务器看不到哈希部分,只有javascript能够 )。 所以谷歌使用这个_excaped_fragment_ 告诉服务器它正在尝试缓存哪个页面。

    更多解释请使用link

    至于为什么会出现 404 错误,我认为是因为您使用了 $1 而没有使用捕获块,正确的规则应该是这样的

    location / {
        if ($args ~ "_escaped_fragment_=(.*)") {
            rewrite ^ /snapshots/$1;
        }
    }
    

    但我认为这不会解决您的问题,因为根据您的示例,您没有使用哈希,而是使用了页面的 uri,所以我会将规则重写为类似的内容

    location / {
        # try snapshot, if not found try direct file.
        try_files snapshots$request_uri.html $uri;
    }
    

    【讨论】:

      【解决方案2】:

      这是我在 nginx 中的内容,它工作正常,您可能需要为 index.html 添加一个特殊的(即访问您网站的根目录时)

      if ($args ~ "_escaped_fragment_=/(.+)/?") {
          set $path $1;
          rewrite ^ /snapshots/$path.html;
          break;
      }  
      
      location /snapshots/ {
      internal;
          alias /var/www/snapshots/;
      }
      

      所以http://me.com/?_escaped_fragment_=/about 将访问 /var/www/snaphots/about.html

      如果您使用 html pushstate 而不是 hashbangs,请不要忘记页面中的此元标记:

      meta(name="fragment", content="!")
      

      【讨论】:

        猜你喜欢
        • 2018-12-08
        • 1970-01-01
        • 2021-05-08
        • 1970-01-01
        • 1970-01-01
        • 2019-02-18
        • 2010-12-08
        • 2015-01-21
        • 1970-01-01
        相关资源
        最近更新 更多