如何仅针对Googlebot启用Angular Universal SSR?
仅对Googlebot启用Angular Universal SSR的配置方案
要实现仅当请求来自Googlebot时启用服务端渲染(SSR),其他请求返回客户端渲染的HTML,只需修改server.ts中的路由处理逻辑,通过检查请求的User Agent来分支处理:
import 'zone.js/node'; import { APP_BASE_HREF } from '@angular/common'; import { ngExpressEngine } from '@nguniversal/express-engine'; import * as express from 'express'; import { existsSync } from 'fs'; import { join } from 'path'; import { AppServerModule } from './src/main.server'; // The Express app is exported so that it can be used by serverless Functions. export function app(): express.Express { const server = express(); const distFolder = join(process.cwd(), 'dist/browser'); const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index'; // Our Universal express-engine server.engine('html', ngExpressEngine({ bootstrap: AppServerModule, })); server.set('view engine', 'html'); server.set('views', distFolder); // TODO: implement data requests securely server.get('/api/**', (req, res) => { res.status(404).send('data requests are not yet supported'); }); // Serve static files from /browser server.get('*.*', express.static(distFolder, { maxAge: '1y' })); // 根据User Agent判断是否启用SSR server.get('*', (req, res) => { const userAgent = req.get('User-Agent'); // 检测是否为Googlebot(忽略大小写,覆盖所有变体) const isGooglebot = userAgent ? /googlebot/i.test(userAgent) : false; if (isGooglebot) { // Googlebot请求:使用SSR渲染 res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] }); } else { // 非Googlebot请求:返回客户端渲染的HTML res.sendFile(join(distFolder, indexHtml + '.html')); } }); return server; } function run(): void { const port = process.env['PORT'] || 4000; // Start up the Node server const server = app(); server.listen(port, () => { console.log(`Node Express server listening on http://localhost:${port}`); }); } // Webpack will replace 'require' with '__webpack_require__' // '__non_webpack_require__' is a proxy to Node 'require' // The below code is to ensure that the server is run only when not requiring the bundle. declare const __non_webpack_require__: NodeRequire; const mainModule = __non_webpack_require__.main; const moduleFilename = mainModule && mainModule.filename || ''; if (moduleFilename === __filename || moduleFilename.includes('iisnode')) { run(); } export * from './src/main.server';
关键逻辑说明
- User Agent匹配:正则
/googlebot/i会忽略大小写匹配所有Googlebot相关的请求头,覆盖桌面端、移动端等Googlebot变体 - SSR分支:检测到Googlebot时,保留原有Angular Universal的
res.render逻辑,完成服务端渲染 - 客户端渲染分支:非Googlebot请求直接返回
dist/browser目录下的静态HTML文件,触发客户端Angular应用的加载和渲染
内容的提问来源于stack exchange,提问作者Jason Rich Darmawan
相关产品推荐
相关产品推荐

