Search code examples
djangohttpresponse

How to provide canonical URL with Django HttpResponseRedirect?


This question is very similar to one I just asked href: Can I get Google search results to use/display the final redirect url?, but now the question is specific to Django.

My site has webpage urls that use the following format:

www.mysite.com/id/pretty_title

The front page links to these pages, but the href actually contains some parameters:

 www.mysite.com/id/?some_ugly_parameters_to_let_me_know_what_search_it_is_from

This then redirects to

www.mysite.com/id/pretty_title

which shows the page.

My issue is that Google's search results show the link to the page as the ugly url instead of the pretty redirected one.

What I have learned is that I need to provide a canonical link. But how can I do this when the ugly url page never really exists, at least not as one that I have written?

What happens server side is that the view of the ugly url does a redirect:

return HttpResponseRedirect(pretty_url)

Solution

  • You can just put it as part of the HTML returned from the Django template, in the <head> section. Do you have a base.html in your Django? You can setup a {% block %} as a placeholder for the canonical URL and then set that value in each individual page that {% extends base.html %}

    base.html

    <html>
    <head>
      <link rel="canonical" href="{% block canonical_url %}{% endblock %}">
    </head>
    ...