Search code examples
pythondjangocanonical-link

How can I get Django Absolute url without "www" in domain?


I try to add valid canonical tag to my Django site. So I must add canonical url without query parameter. I find pretty solution, but I have trouble that I could not resolve. My tag is looks like this:

{% if request.GET %}
  <link rel="canonical" href="https://{{ request.get_host }}{{ request.path }}">
{% endif %}

This is good solution, but in real site in page with url https://example.com/about-us?page=3 I get this canonical url https://www.example.com/about-us

Why i get canonical url with www before site domain

This is my ALLOWED_HOST in settings.py:

ALLOWED_HOSTS = [
    '127.0.0.1',
    'www.example.com',
    'example.com',
    'localhost',
]

How can i get valid canonical url without www?


Solution

  • Because you are using request.get_host, that is going to resolve to whatever the user typed into the browser. You probably have your DNS records set up to accept the domain either with or without www. Django doesn't care what domain it's serving, except/unless you are using its Sites framework (your sample code does not touch the Sites framework, so I'm guessing you aren't). Therefore, Django responds based on the URL path alone, and ignores the domain.

    Are you asking if you can have "www" stripped from the inbound request? Sure, you can do that at the web server (apache/nginx etc.) layer with redirects specific to those web servers. Or you can let the request through the web server and intercept it at the app server layer (Django) with custom middleware. Here is an example of that.

    Note you cannot use the Redirects app built into Django because it only operates on paths, whereas you want to manipulate the incoming domain itself.

    So, your choice: Tweak your web server, or add a middleware module to your Django project.

    The ALLOWED_HOSTS setting is unrelated to your question.

    Aside: Your question is a bit confusing because you first ask about the removed query parameter ?page=3 but then you switch to asking about www in the domain. If you are asking about query params, please edit your question, as that warrants a different answer.