doniyor
doniyor

Reputation: 37876

django catching http-referer not working always

if 'HTTP_REFERER' in request.META and 'mysite.com' not in request.META['HTTP_REFERER'] or 'HTTP_REFERER' not in request.META:
    return redirect('/')

if HTTP_REFERER is there and if it doesnot contain mysite.com or if HTTP_REFERER not given, it should redirect to startpage.

my code is deployed over 7 servers, scheduled via loadbalancer, the code in all those 7 servers are uptodate. but still, only sometimes, this redirect is not working.

what may I be doing wrong?

the case, where it is not working:

one newssite published a news about my page and pasted a deep link from my page. and I clicked on that link, and it didnot redirect. I got surprised and checked my code, everything was ok, and clicked again on the link and bingo, this time it did redirect me to startpage. I was happy, I thought it may be a caching or smthg. but later, I clicked on the link and the redirect didnot work again. then posted this question. the case is independent of browser type and version.

Upvotes: 1

Views: 1521

Answers (1)

Matt Seymour
Matt Seymour

Reputation: 9395

Firstly, this code could be shortened too:

if 'mysite.com' not in request.META.get('HTTP_REFERER', ''):
    return redirect('/')

Secondly, HTTP_REFERER is not guaranteed to be present. It might just be users are using bookmarks, or browser autocomplete which will mean the HTTP_REFERER may or may not be present in the cases you are testing.

If a valid user of the site who uses a bookmark will be redirected. Likewise an invalid user who gets referred from somedomain.com/mysite.com will be redirected. In this case it might be better to use a startwith() when checking the referer. Is there not a better way you can manage what you are trying to do.

Maybe you can update the question with a little more context. I will be willing to help you as best as I can.

Upvotes: 2

Related Questions