You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony命令开发:自动更新robots.txt排除指定分类页面

Symfony命令实现自动更新robots.txt排除非公开分类页面

咱们可以完善这个RobotExcludedJournalsCommand命令,实现自动识别数据库中标记为非公开(public字段为false)的分类页面,并将它们添加到robots.txt的Disallow规则里。以下是完整的实现代码和说明:

完整命令代码实现

<?php

namespace YourBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class RobotExcludedJournalsCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('webmain:robot_excluded_category_command')
            ->setDescription('自动更新robots.txt,排除非公开的分类页面');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // 获取实体管理器,替换成你的分类实体类
        $em = $this->getContainer()->get('doctrine.orm.entity_manager');
        $excludedCategories = $em->getRepository('YourBundle:Category')
            ->findBy(['public' => false]);

        // 定义robots.txt文件路径
        $robotsPath = $this->getContainer()->getParameter('kernel.root_dir') . '/../web/robots.txt';

        // 读取现有robots内容,保留原有规则,只替换分类排除部分
        $existingContent = file_get_contents($robotsPath);
        // 定义标记,用于定位要替换的区块
        $startMarker = "# --- START EXCLUDED CATEGORIES ---";
        $endMarker = "# --- END EXCLUDED CATEGORIES ---";

        // 构建新的排除规则
        $exclusionRules = [$startMarker];
        foreach ($excludedCategories as $category) {
            // 替换成你的分类页面URL路径,比如'/category/' . $category->getSlug()
            $categoryPath = '/category/' . $category->getSlug();
            $exclusionRules[] = "Disallow: $categoryPath/";
            $exclusionRules[] = "Disallow: $categoryPath/*";
        }
        $exclusionRules[] = $endMarker;
        $newExclusionBlock = implode("\n", $exclusionRules);

        // 替换原有区块,如果不存在则追加到文件末尾
        if (strpos($existingContent, $startMarker) !== false && strpos($existingContent, $endMarker) !== false) {
            $pattern = '/' . preg_quote($startMarker, '/') . '.*?' . preg_quote($endMarker, '/') . '/s';
            $updatedContent = preg_replace($pattern, $newExclusionBlock, $existingContent);
        } else {
            $updatedContent = $existingContent . "\n\n" . $newExclusionBlock;
        }

        // 写入更新后的内容
        file_put_contents($robotsPath, $updatedContent);

        $output->writeln(sprintf('已成功更新robots.txt,共排除%d个非公开分类页面', count($excludedCategories)));
    }
}

使用说明

  • 替换代码中的YourBundle和Category实体为你项目中实际的命名空间和实体类
  • 调整$categoryPath的生成逻辑,匹配你站点分类页面的URL结构
  • 执行命令更新robots.txt:
sudo php app/console webmain:robot_excluded_category_command

注意事项

  • 确保web目录下的robots.txt有可写权限,使用sudo执行命令可以避免权限问题
  • 代码中使用了标记区块来管理排除规则,这样不会覆盖robots.txt中的其他自定义规则
  • 可以考虑添加日志记录,或者在写入前备份原文件,避免意外情况导致文件损坏

内容的提问来源于stack exchange,提问作者Strahinja90bg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:10:55