【问题标题】:How to do a simple captive portal with django http redirects?如何使用 django http 重定向做一个简单的强制门户?
【发布时间】:2013-07-14 03:37:44
【问题描述】:

我有一台运行 django 并提供无线接入点的设备。我基本上想创建一个强制门户,输入的任何 url 都会转到我的 django 网页。

到目前为止,为了实现这一点,我已经创建了一个像这样的 iptables 规则(现在):

iptables -t nat -A PREROUTING -d 0/0 -p tcp –dport 80 -j DNAT –to 192.168.50.1:8000 

这在某种程度上是有效的,除了如果我去例如“google.com”,我会在浏览器 url 中显示 google.com,但会显示我的 django 网页。

我希望 mydjangowebpage.com 改为显示在 url 中。似乎有许多强制门户解决方案需要 dns 服务器、多个 iptables 规则、radius 服务器等。

对我来说,一个简单的解决方案似乎是执行我上面指定的一条规则,然后在 django 中执行一些 httpredirect 命令。我想知道我的 urls.py 调度程序是否能够检查实际的站点 url(即“google.com”部分),以及是否不是“mydjangowebpage.com”来对“mydjangowebpage”进行 httpredirect。那有意义吗?

我猜 urlpatterns 会查找匹配项,看来要完成此操作,模式需要查找不匹配项并查看整个 url,而不仅仅是站点名称后面的内容。

例如,类似于以下内容的内容:

urlpatterns = patterns('',
    url(lambda x: not models.get_current_site(request) == 'mydjangowebpage.com', lambda x: HttpResponseRedirect("http://mydjangowebpage.com")),
    ....

【问题讨论】:

    标签: django redirect iptables


    【解决方案1】:

    好吧,我找到了一种方法。如果有更好的方法,我仍然会保持打开状态...

    您可以使用中间件过滤器。我发现这个here 可以工作(称为hostname_middleware.py)。为了方便起见,我在这里复制了它:

    from django.conf import settings
    from django.utils.http import urlquote
    from django import http
    
    class EnforceHostnameMiddleware(object):
        """
        Enforce the hostname per the ENFORCE_HOSTNAME setting in the project's settings
        The ENFORCE_HOSTNAME can either be a single host or a list of acceptable hosts
        """
        def process_request(self, request):
            try:
                if not settings.ENFORCE_HOSTNAME:
                    return None
            except AttributeError, e:
                return None
    
            host = request.get_host()
    
            # find the allowed host name(s)
            allowed_hosts = settings.ENFORCE_HOSTNAME
            if not isinstance(allowed_hosts, list):
                allowed_hosts = [allowed_hosts]
            if host in allowed_hosts:
                return None
    
            # redirect to the proper host name
            new_url = [allowed_hosts[0], request.path]
            new_url = "%s://%s%s" % (
                request.is_secure() and 'https' or 'http',
                new_url[0], urlquote(new_url[1]))
            if request.GET:
                new_url += '?' + request.META['QUERY_STRING']
    
            return http.HttpResponsePermanentRedirect(new_url)
    

    然后添加您的 settings.py 文件(根据您的需要进行定制):

    ENFORCE_HOSTNAME=['192.168.50.1','mydjangowebpage.com']
    

    并将中间件添加到 MIDDLEWARE_CLASSES:

    'mydjangowebpage.hostname_middleware.EnforceHostnameMiddleware'
    

    现在,当我转到“facebook.com”或其他任何 URL 时,它会将名称重定向到列表中的第一个。耶!简单的强制门户!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多