Using the Django-auth application (Django version 1.3), I want to have my login page go to https://mysite.com/login/. Currently, I’m using:
# urls.py
from django.contrib.auth.views import login
urlpatterns = patterns('', url(r'^login/$', login, name='login-view'),)
# navbar.html
<li id="nav-login"><a href="{% url login-view %}" ><b>Login</b></a></li>
which works nicely, but goes to http://mysite.com/login/.
Is there some way to tell Django-auth what prefix (https) to use, when it reverses the view name? I’ve read the entire manual page, and haven’t found anything that covers it. Or maybe some way to tell the url tag to go to https?
Or is the only option to specify the entire URL manually? I hope not 🙂 And given how powerful Django has been so far, I can’t believe it wouldn’t have that ability – I must be overlooking it. 🙂
Set OS environmental variable HTTPS to on
You need to enable the OS environmental variable
HTTPSto'on'so django will prepend https to fully generated links (e.g., like withHttpRedirectRequests). If you are using mod_wsgi, you can add the line:to your wsgi script. You can see the need for this by reading
django/http/__init__.py:Secure your cookies
In settings.py put the lines
and cookies will only be sent via HTTPS connections. Additionally, you probably also want
SESSION_EXPIRE_AT_BROWSER_CLOSE=True. Note if you are using older versions of django (less than 1.4), there isn’t a setting for secure CSRF cookies. As a quick fix, you can just have CSRF cookie be secure when the session cookie is secure (SESSION_COOKIE_SECURE=True), by editingdjango/middleware/csrf.py:Direct HTTP requests to HTTPS in the webserver
Next you want a rewrite rule that redirects http requests to https, e.g., in nginx
Django’s
reversefunction and url template tags only return relative links; so if you are on an https page your links will keep you on the https site.