【问题标题】:Django + Azure: How to implement a 301 redirect from naked to www domainDjango + Azure:如何实现从裸到 www 域的 301 重定向
【发布时间】:2021-06-02 04:07:23
【问题描述】:

我在 Microsoft Azure 上运行 Django 应用程序,需要 301 将所有流量重定向到单个安全 www 域,即

发件人:

http://example.com
https://example.com 
http://www.example.com

收件人:

https://www.example.com

我假设我需要使用服务器配置文件设置重定向,但我是 Azure 新手,不知道如何去做。该网站在 Linux 上运行。

另外,我只设置了 https,所以 http 请求当前被定向到 https。

感谢您的帮助!

【问题讨论】:

  • 你使用哪个平台,linux还是windows?
  • Jason,我们使用的是Linux平台
  • 您可以尝试Doris的建议,也可以尝试添加.htaccess文件。

标签: django azure redirect azure-web-app-service


【解决方案1】:

我采用的解决方案实施起来非常简单,在

How to Make Django Redirect WWW to Your Bare Domain

总结

  1. 在您的某个应用(例如 myapp)中创建一个新的中间件文件

    从 django.http 导入 HttpResponsePermanentRedirect

     class WwwRedirectMiddleware:
         def __init__(self, get_response):
             self.get_response = get_response
    
         def __call__(self, request):
             host = request.get_host().partition(':')[0]
             if host == "www.example.com":
                 return HttpResponsePermanentRedirect(
                     "https://example.com" + request.path
                 )
             else:
                 return self.get_response(request)
    
  2. 为允许的主机调整您的 settings.py 文件

    ALLOWED_HOSTS=[ # ... "example.com", "www.example.com", # ... ]

  3. 在 SecurityMiddleware 之后添加尽可能高的中间件引用

    中间件 = [ "django.middleware.common.CommonMiddleware", "django.middleware.security.SecurityMiddleware", "myapp.middleware.WwwRedirectMiddleware", # ... ]

【讨论】:

    【解决方案2】:
    1. Django 有重定向应用程序https://docs.djangoproject.com/en/dev/ref/contrib/redirects/

    Django 带有一个可选的重定向应用程序。它可以让你存储 在数据库中重定向并为您处理重定向。它用 HTTP 响应状态码默认为 301 Moved Permanently。

    1. 您可以考虑一个名为Application Gateway的服务:Redirect web traffic

    2. 您可以使用 HttpResponseRedirect 重定向流量,但这将返回 http 302 而不是 301。

    【讨论】:

    • 谢谢多丽丝。您的解决方案 3 对我来说是最好的,它可以像我发布的答案一样进行改进,使用函数 HttpResponsePermanentRedirect 使其成为 301
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2020-02-05
    • 2015-01-07
    • 2016-01-15
    • 2011-04-01
    • 2014-03-29
    • 2013-12-21
    相关资源
    最近更新 更多