Question about @login_required decorator and the redirect type
By default, when using the @login_required
decorator, Django performs a 302 (temporary) redirect when redirecting a non-authenticated user to the login page. I work in conjunction with an SEO company (I know not开发者_StackOverflow中文版hing of the topic myself) and he insists that the 301 (permanent) redirect is essential to the work that he is doing.
Is there anyway to force Django to perform a 301 redirect while using the @login_required decorator?
Thanks again.
The @login_required
decorator uses the redirect_to_login
view, which returns a Django HttpResponseRedirect
object to redirect the user to the login page. This object represents, as you mention, a 302 redirect. There is an alternative redirect object, the HttpResponsePermanentRedirect
, though you would need to write your own decorator which uses this instead.
Writing your own decorator is, of course, possible. It would be bad practice though, in my opinion. Not least because it ties your app to a particular implementation of the authentication module, but also because a 302 redirect is actually the correct one to use in this case.
The fact is that the page has not "moved permanently". Instead, the user simply needs to authenticate himself/herself before accessing the same URL once again. For this reason, the redirect is not a permanent one, as the page has not actually "moved".
login_required
usesuser_passes_test
, which in turn callsredirect_to_login
in which theHttpResponseRedirect
is hard-wired.
So no, the type of redirect cannot be changed just using login_required
alone. You could write your own login_required decorator to provide 301 redirect (although the use of this here is disputable).
精彩评论