I want to build a canonical url for my website: my.com
here are the requirements:
- always include www subdomain
- always use https protocol
- remove default 80 and 443 ports
- remove trailing slash
Example:
http://my.com => https://www.my.com
http://my.com/ => https://www.my.com
https://my.com:80/ => https://www.my.com
https://sub.my.com/ => https://sub.my.com
https://sub.my.com?term=t1 => https://sub.my.com?term=t1
This is what I have tried:
from urllib.parse import urlparse, urljoin
def build_canonical_url(request):
absolute = request.build_absolute_uri(request.path)
parsed = urlparse(absolute)
parsed.scheme == 'https'
if parsed.hostname.startswith('my.com'):
parsed.hostname == 'www.my.com'
if parsed.port == 80 or parsed.port == 443:
parsed.port == None
# how to join this url components?
# canonical = join parsed.scheme, parsed.hostname, parsed.port and parsed.query
But I don't know how to join these url components?