Skip to content Skip to sidebar Skip to footer

Canonical Links And 301 Redirect If Url Doesn't Match Slug

I am trying to implement a URL scheme similar to stack overflow's in django/python. E.g. the pk is stored in the URL along with a slug of the title so for this question (id #478773

Solution 1:

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

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: I'd do it the straight forward way. Define a non unique slug field and compare vs the captured URL in your detail view.

# modelsclassMyModel(models.Model):
    # ...
    non_unique_slug = models.SlugField()

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


# urlsr'^questions/(?P<id>\d+)/(?P<slug>[\w-]+)/$'# viewsdefmy_view(request, id, slug):
    page = Page.objects.get(id=id)
    ifnot slug == page.slug:
        return http.HttpResponsePermanentRedirect(page.get_absolute_url())

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

Solution 2:

I followed Yuji's helpful instructions but found that you'll need to use the HttpResponsePermanentRedirect object to get a permanent 301 instead of the temporary 302.

Post a Comment for "Canonical Links And 301 Redirect If Url Doesn't Match Slug"