[Fixed]-DisallowedRedirect (Unsafe redirect to URL with protocol) Django

28👍

instead of

return HttpResponseRedirect('news:home',request)

this:

return HttpResponseRedirect(reverse('news:home'))

or

return redirect('news:home')

or

return redirect(reverse('news:home'))

10👍

HttpResponseRedirect.allowed_schemes.append(‘news’)

6👍

In addition to the current answers if you want to redirect to an custom scheme, you can use following code:

class CustomSchemeRedirect(HttpResponsePermanentRedirect):
    allowed_schemes = ['tg']


def redirect(request):
    return CustomSchemeRedirect('tg://resolve?domain=durov')
👤Andrei

3👍

Make sure that when you get this error you have the correct scheme supplied in front of your URL. By default the django.http.HttpResponseRedirect does not allow redirects to URLs that don’t start with one of the following schemes:

  • http
  • https
  • ftp

So if the URL you supply is, for example, localhost:8000 make sure you change it to http://localhost:8000 to get it to work.

👤Bono

0👍

Don’t forget that apart from enabling the redirect, nowadays Safari won’t open your redirected deep links unless you do the work outlined here: https://developer.apple.com/documentation/xcode/supporting-associated-domains

  1. Add the url path into your Django app:
path('.well-known/apple-app-site-association', views.web.links.appleAppSiteAssociation, name='.well-known/apple-app-site-association'),
  1. The view should return a JSON response:

def appleAppSiteAssociation(request_):
   """
   Tell Apple that certain URL patterns can open the app
   :param request_:
   :return:
   """
   json = {
     "applinks": {
         "details": [
              {
                "appIDs": ["MY.APP.BUNDLEID"],
                "components": [
                  {
                     "#": "no_universal_links",
                     "exclude": True,
                     "comment": "Matches any URL whose fragment equals no_universal_links and instructs the system not to open it as a universal link"
                  },
                  {
                     "/": "/dataUrl=*",
                     "comment": "Matches any URL whose path starts with /dataUrl="
                  },

                ]
              }
          ]
      },
      "webcredentials": {
         "apps": ["MY.APP.BUNDLEID"]
      },
   }

   return JsonResponse(json)
  1. Add the webcredentials:MYPROTOCOL into the Associated Domains in XCode

Leave a comment