【问题标题】:Django app should redirect to same IP but different portDjango 应用程序应该重定向到相同的 IP 但不同的端口
【发布时间】:2017-10-11 23:28:28
【问题描述】:

让 Django 在 https 端口 (443) 上运行。当用户访问https://hostname/newAPP时,我希望Django重定向到https://hostname:port

我在 urls.py 的 urlpatterns 中尝试了以下行,但无法得到结果。

url(r'^newAPP$', RedirectView.as_view(url=':8000', permanent=True), name='NewApp')

实际上它正在被重定向,但是到了一个格式错误的 url “https:hostname/:8000”。请注意,“:”放在“/”之后。

服务器有多个 IP/主机名,因此无法对 IP/主机名进行硬编码。

【问题讨论】:

    标签: django url-redirection


    【解决方案1】:

    好吧,您的示例不起作用,因为您在 localhost:2000/ 之后重定向,您可以使用以下内容创建一个视图以重定向到另一个域:

    在 urls.py 中:

    url(r'^newAPP', views.redirect, {'var': 2000}),
    url(r'^anotherAPP', views.redirect, {'var': 3000}), #Of course you can use this view for more than one app
    

    在你看来:

    def redirect(request, **kwargs):
        return HttpResponseRedirect('https://localhost:%s' % kwargs.get('var'))
    

    如果你不喜欢这种方式,你可以使用服务器。下一个例子是 nginx:

    server {
        . . .
        server_name example.com www.example.com;
    
        rewrite ^/newAPP$ https://localhost:2000 permanent;
        rewrite ^/anotherAPP$ https://localhost:3000 permanent;
        . . .
    }
    

    更多关于nginx redirects 的信息。告诉我这对你有没有帮助

    【讨论】:

    • 它适用于端口重定向......但硬编码 IP/主机名不是一个选项,因为服务器有多个 IP 地址。如果有避免在视图中提及 localhost/ip/hostname 的解决方案,那就太好了。
    • 然后只需在变量 var 中添加完整的域,并在重定向中剪切除 var 之外的所有域
    【解决方案2】:

    在您的基本urls.py 文件中,您可以添加以下内容以创建一个重定向到同一IP 上不同端口的视图。

    我没有对这段代码进行广泛的测试,但它现在对我有用。如果有人想稳健地重定向到不同的端口,我将不胜感激。

    from django.shortcuts import redirect
    
    def get_new_url(request):
        # Specify the port number, you could get this dynamically
        # through a config file or something if you wish
        new_port = '5000'
    
        # `request.get_host()` gives us {hostname}:{port}
        # we split this by colon to just obtain the hostname
        hostname = request.get_host().split(':')[0]
        # Construct the new url to redirect to
        url = 'http://' + hostname + ':' + new_port + '/'
        return redirect(url)
    
    urlpatterns = [
        # Some other paths
        path('something/', views.some_view, name='something')
        # ...
        # ...
    
        # Add your redirect
        path('newAPP/', get_new_url, name='newapp'),
    
    ]
    

    如果您愿意,函数get_new_url() 可以存在于views.py 文件中。只需确保在 urlconf 中引用它之前将其导入即可。

    【讨论】:

      猜你喜欢
      • 2019-08-11
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多