防止谷歌索引AngularJS路由

Prevent Google indexing an AngularJS route

本文关键字:AngularJS 路由 索引 谷歌      更新时间:2023-09-26

通常,如果我不想让谷歌抓取页面,我会将页面添加到我的机器人.txt文件中,如下所示:

User-agent: *
Disallow: /my-page

为了防止 Google 将该网页编入索引,我会从我的sitemap.xml中删除该网页,并在该网页的<head>中添加以下元标记:

<meta name="robots" content="noindex">

现在,如果我使用 AngularJS 来处理单页应用程序的所有路由,如何停止 Google 索引和/或抓取路由?Angular 在 ng-view 中为每条路线带来内容,因此<head>中的信息在每条路线上都保持不变。我认为在这种情况下我不能添加元标记。

如果根模块放在 <html> 标记 ( <html ng-app="myApp"> ) 上,则可以修改<head>中的所有属性。这允许您为每个页面动态设置机器人<meta>。您可以使用根模块中的 $routeChangeSuccess 事件执行此操作。如果您使用的是 ui-router,则可以在路由上设置一个"data"属性,您可以在每次状态更改时读取该属性。还可以使用 $rootScope 从其他模块更新此值,但这不是一个好的做法。最好的方法是从子控制器/指令广播对根模块的更改。

我有一个动态更改页面<title>的示例,但它有点复杂,因为此应用程序是手动引导的。但是,假设<html>标签上有一个 ng-app=" 和 ng-controller=" 指令。

下面是状态更改事件:https://github.com/danmindru/angular-boilerplate-study/blob/master/src/app/_app-main/_app-main.controller.js#L14-L24

以下是广播的侦听器:https://github.com/danmindru/angular-boilerplate-study/blob/master/src/app/_app-main/_app-main.controller.js#L38-L40

以下是触发广播的方式: https://github.com/danmindru/angular-boilerplate-study/blob/master/src/app/profile-feature/customer-page/customer-page.controller.js#L12

下面是绑定<title>:https://github.com/danmindru/angular-boilerplate-study/blob/master/src/index.html#L4

但是,Google并不擅长读取这些属性,因此您必须使用预渲染服务来确保googlebot将解析<meta name="robots" content="noindex">而不是<meta name="robots" content="{{index}}">之类的东西。