规范链接和301重定向如果URL不匹配s。 [英] Canonical links and 301 Redirect if URL doesn't match slug

查看:173
本文介绍了规范链接和301重定向如果URL不匹配s。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在django / python中实现类似于stack overflow的URL方案。

I am trying to implement a URL scheme similar to stack overflow's in django/python.

例如。 pk与URL一起存储在URL中,所以对于这个问题(id#4787731),URL是

E.g. the pk is stored in the URL along with a slug of the title so for this question (id #4787731) the URL is

https://stackoverflow.com/questions/4787731/canonical-links-and-301-redirect-if-url-doesnt-match-slug

如果我后来更改了标题(或者只是将url放入一些随机垃圾),那么网站仍然会知道我之后的哪个问题(由ID),并且301将重定向到正确的URL - 例如尝试。

If I later change the title (or just put in some random crud into the url) then the site will still know which question I am after (by the ID) and will 301 redirect to the correct URL - e.g. try.

https://stackoverflow.com/questions/4787731/canonical-links-MODIFIED-URL

所以


  • 在我的页面中包含规范链接的最佳方式是什么,例如

  • What is the best way to include canonical links in my pages such as

< link rel =canonicalhref =https://stackoverflow.com/questions/ 4787731 / canonical-links-and-301-redirect-if-url-doesnt-match-slug>

<link rel="canonical" href="https://stackoverflow.com/questions/4787731/canonical-links-and-301-redirect-if-url-doesnt-match-slug">

(我可以使用get_absolute_url)

(can I use get_absolute_url)


  • 什么是最好的方法来认识到当前的URL与规范链接不匹配并发出一个301 ?

注意 - 这个问题是类似的,但只涉及在飞行中或静态地生成lug。

推荐答案

1:如果有301s,我不认为使用规范标签有一点。

1: I don't think there's a point in using the canonical tag if there are 301s anyways.

让我们想象一下,将URL从 / q / 111 / hello-world 更改为 / q / 111 / foobar的。引擎不会假设这两个是相等的,除非他们访问原始的网址,其上的标准标签指向 / q / 111 / foobar (它不会,因为它是现在是一个301,切断页面之间的任何关系的证据)。

Let's just imagine a scenario where you change the URL from /q/111/hello-world to /q/111/foobar. The engines won't assume the two are equal unless they visit the original url with the canonical tag on it pointing to /q/111/foobar (which it wont, because it's now a 301, severing any proof of a relationship between the pages).

2:我会直接做到这一点。定义非唯一的 slug 字段,并与详细视图中的捕获的URL进行比较。

2: I'd do it the straight forward way. Define a non unique slug field and compare vs the captured URL in your detail view.

# models
class MyModel(models.Model):
    # ...
    non_unique_slug = models.SlugField()

    def get_absolute_url(self):
        return "/questions/%s/%s" % (self.id, self.non_unique_slug)


# urls
    r'^questions/(?P<id>\d+)/(?P<slug>[\w-]+)/$' 

# views
def my_view(request, id, slug):
    page = Page.objects.get(id=id)
    if not slug == page.slug:
        return http.HttpResponsePermanentRedirect(page.get_absolute_url())

    # render page
    return direct_to_template(request, "foobar.html", {'page': page})

这篇关于规范链接和301重定向如果URL不匹配s。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆