2014-05-10 21 views
2

我很想知道是否有一個Symfony2的方式有env特定的robots.txt文件。 當robots.txt文件位於Web(根目錄)目錄中時,所有env都是相同的。 我知道這樣做的唯一方法是從Web目錄中刪除文件,並使用env特定的路由文件爲機器人文件定義路由,並在控制器中創建一個函數來恢復該文件。Symfony2 env特定的robots.txt

那麼有沒有一種Symfony2的方式來讓env特定的robots.txt文件以更「酷」的方式。

謝謝你的時間。 最好的問候, 格奧爾基。

回答

4

可以使用FrameworkBundle:Template:template控制器來呈現基於對環境的樹枝文件:

在你的路由陽明文件:

acme_robots: 
    path: /robots.txt 
    defaults: 
     _controller: FrameworkBundle:Template:template 
     template: AcmeBundle:Static:robots_%kernel.environment%.txt.twig 
+0

不要忘了刪除原來的web/robots.txt文件以獲得symfony路由控制 –

+0

您可以將'_format:txt'添加到'defaults'以將其作爲'text/plain',而不是'文/ html'。 – ACJ

0

以前的答案是相當不錯的,但有一個問題。 Robots.txt將返回Content-type: text/html

要返回robots.txtContent-type: text/plain我們需要做下一件事情。

routing.yml

app_robots: 
    pattern: /robots.txt 
    defaults: 
     _controller: AppBundle:Static:robots 
     # template: AppBundle:Static:robots_%kernel.environment%.txt.twig 

src/AppBundle/Controller/StaticController.php

<?php 

namespace AppBundle\Controller; 

use Symfony\Component\HttpFoundation\Response; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 

/** 
* StaticController controller. 
*/ 
class StaticController extends Controller 
{ 
    /** 
    * Displays robots.txt. 
    */ 
    public function robotsAction($template = null) 
    { 
     $response = new Response(); 
     $response->headers->set('Content-Type', 'text/plain'); 

     return $this->render($template ?: sprintf(
      "AppBundle:Static:robots_%s.txt.twig", 
      $this->container->getParameter('kernel.environment') 
     ), array(), $response); 
    } 
} 

AppBundle/Resources/views/Static/robots_prod.txt.twig

# Production robots.txt 

User-agent: * 
Allow:/

AppBundle/Resources/views/Static/robots_staging.txt.twig

# Staging robots.txt 

User-agent: * 
Disallow:/
0

RobotsBundle允許通過配置變量來防止測試/開發環境的索引。只需添加到您的config_test.yml/config_dev.yml:

four_labs_robots: 
    block_all: true 

它將然後添加X-Robots-Tag: none HTTP header到所有響應。