31

这是我目前提供 robots.txt 的方法

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

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

http://my.domain.com/static/stuff-here

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

 TemplateView.as_view(template_name='robots.txt',
                                  content_type='text/plain')

看起来比仅对我在 nginx 上提供的静态目录的静态调用更消耗资源。

4

2 回答 2

64

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

location  /robots.txt {
    alias  /path/to/static/robots.txt;
}

有关更多信息,请参见此处:https ://nginx.org/en/docs/http/ngx_http_core_module.html#alias

如果你有 favicon.ico 文件,同样的事情也适用。

Apache 配置的等效代码是:

Alias /robots.txt /path/to/static/robots.txt
于 2013-08-25T00:09:26.347 回答
13

我知道这是一个迟到的回复,当我无法访问 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"),
]

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

于 2016-09-23T13:54:16.993 回答