django有效地服务robots.txt

Luc*_*ang 17 python django robots.txt

这是我目前服务robots.txt的方法

url(r'^robots\.txt/$', TemplateView.as_view(template_name='robots.txt',
                                            content_type='text/plain')),
Run Code Online (Sandbox Code Playgroud)

我不认为这是最好的方式.我认为如果它只是一个纯粹的静态资源并静态服务会更好.但我的django应用程序的结构方式是静态根和所有后续静态文件都位于

http://my.domain.com/static/stuff-here
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?我是django的业余爱好者

 TemplateView.as_view(template_name='robots.txt',
                                  content_type='text/plain')
Run Code Online (Sandbox Code Playgroud)

看起来比在nginx上提供的静态目录的静态调用消耗更多的资源.

Han*_*ody 46

是的,如果文件是静态的,Django不应该提供robots.txt.在你的Nginx配置文件中尝试这样的事情:

location  /robots.txt {
    alias  /path/to/static/robots.txt;
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此处:http://wiki.nginx.org/HttpCoreModule#alias

同样的事情适用于favicon.ico文件,如果你有一个.

  • 为什么要由Nginx提供服务? (3认同)

Ste*_*ett 6

我知道这是一个较晚的答复,当我无法访问Web服务器配置时,我正在寻找类似的解决方案。因此,对于寻找类似解决方案的其他人,我找到了以下页面:http : //www.techstricks.com/adding-robots-txt-to-your-django-project/

建议将其添加到您的项目url.py中:

from django.conf.urls import url
from django.http import HttpResponse

urlpatterns = [
    #.... your project urls
    url(r'^robots.txt', lambda x: HttpResponse("User-Agent: *\nDisallow:", content_type="text/plain"), name="robots_file"),
]
Run Code Online (Sandbox Code Playgroud)

我认为这应该比使用模板文件更有效,尽管如果需要多个“ Disallow:”选项可能会使您的url规则混乱。