在Django中,我將SESSION_COOKIE_DOMAIN設置爲我的域名。但我實際上想用兩個不同的域名運行同一個站點。Django,具有多個域的SESSION_COOKIE_DOMAIN
通過設置SESSION_COOKIE_DOMAIN,只有指定的域允許用戶登錄。是否有可能允許兩個域名登錄?
在Django中,我將SESSION_COOKIE_DOMAIN設置爲我的域名。但我實際上想用兩個不同的域名運行同一個站點。Django,具有多個域的SESSION_COOKIE_DOMAIN
通過設置SESSION_COOKIE_DOMAIN,只有指定的域允許用戶登錄。是否有可能允許兩個域名登錄?
如果您將會話cookie域設置爲以「。」開頭。字符,它可以讓你處理通配符子域,並跨多個子域共享會話cookie(登錄會話)。
In settings.py: SESSION_COOKIE_DOMAIN=".stackoverflow.com"
以上將允許cookie跨user1.stackoverflow.com和user2.stackoverflow.com共享。
如果你確實希望url對於同一個站點來說是不同的,你想讓同一個用戶在一個登錄會話中在兩個站點之間切換嗎?或者你是否希望能夠讓兩個不同的用戶從兩個不同的URL(不是子域?)登錄到該站點?
標準SessionMiddleware只支持一個SESSION_COOKIE_DOMAIN,它只適用於一個域和子域它們。
下面是一個變體,它將根據請求主機動態設置Cookie域。要使用它,只需更新MIDDLEWARE_CLASSES即可使用這一個SessionHostDomainMiddleware,而不是SessionMiddleware。這更好,@jcdyer和@interstar?
import time
from django.conf import settings
from django.utils.cache import patch_vary_headers
from django.utils.http import cookie_date
from django.contrib.sessions.middleware import SessionMiddleware
class SessionHostDomainMiddleware(SessionMiddleware):
def process_response(self, request, response):
"""
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie.
"""
try:
accessed = request.session.accessed
modified = request.session.modified
except AttributeError:
pass
else:
if accessed:
patch_vary_headers(response, ('Cookie',))
if modified or settings.SESSION_SAVE_EVERY_REQUEST:
if request.session.get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = request.session.get_expiry_age()
expires_time = time.time() + max_age
expires = cookie_date(expires_time)
# Save the session data and refresh the client cookie.
# Skip session save for 500 responses, refs #3881.
if response.status_code != 500:
request.session.save()
host = request.get_host().split(':')[0]
response.set_cookie(settings.SESSION_COOKIE_NAME,
request.session.session_key, max_age=max_age,
expires=expires, domain=host,
path=settings.SESSION_COOKIE_PATH,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None)
return response
我認爲這是你在找什麼,我帶我小時找出來
取代具有完整的新SessionMiddleware你可以改變響應cookie爲以下幾點:
class CrossDomainSessionMiddleware(object):
def process_response(self, request, response):
if response.cookies:
host = request.get_host()
# check if it's a different domain
if host not in settings.SESSION_COOKIE_DOMAIN:
domain = ".{domain}".format(domain=host)
for cookie in response.cookies:
if 'domain' in response.cookies[cookie]:
response.cookies[cookie]['domain'] = domain
return response
(將此中間件放置在會話中間件上方)如果您願意,可以將其限制在特定域中。
我想要第二個。不是子域。基本上我有一個客戶誰averylongdomainnamethatno-onewantstotype.net和quickname.net和該網站需要爲兩者工作。 – interstar 2010-01-27 11:55:53
如何將'longname.net'重定向到'shortname.net'以便所有用戶只使用'shortname.net'? – 2013-08-03 03:25:20
也可以在'example.com'和'www.example.com'之間使用。 – 2017-01-23 16:07:20