在Django中使用子域 [英] Using subdomains in django

查看:60
本文介绍了在Django中使用子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我是否可以(如果可以,如何)将每个用户子域用于页面。例如,现在我具有以下形式的URL: http://hostname.com/user/1 我需要获取 http://username.hostname.com/

Please tell me whether it is possible (if so, how) to use for pages each user subdomains. For example, now I have a URL of the form: http://hostname.com/user/1 I need to get http://username.hostname.com/

推荐答案

您有很多选择,具体取决于您要深入的程度。

You have a number of options depending on how in-depth you want to go.


  1. 一个选项是在Web服务器级别处理路由。基本上,您将捕获URL的子域部分,并将其重写到服务器中的其他位置。

  1. One option is to handle the routing at the web server level. Basically you will capture the subdomain part of the URL and rewrite it to a different location within your server.

例如 http:// username1。您的网络服务器将捕获local.host/signin 并将其内部路由到资源,例如 / username1 / signin 。最终用户将成为子域,但是您的代码将处理url部分,而不是处理已发生的事情。

For example http://username1.local.host/signin will be captured by your webserver and internally routed to a resource such as /username1/signin. The end user will subdomains but your code will handle url parts be none the wiser as to what has happened.

您的urls.py然后将像处理任何普通请求一样处理此问题。

Your urls.py will then handle this like any normal request.

url_pattern = [
   ...
   url(r'(?P<subdomain>[a-z]+)/sigin/$', 'view'),
]

对于Nginx您将需要研究从子域到子目录的重写。

For Nginx you will need to look into "subdomain to subdirectory re-writing".

我个人将使用该选项来解决您的问题。尽管此方法最初设置起来比较棘手(请继续使用,直到它起作用为止)。从长远来看,它将更加容易维护和使用。

I would personally use this option for what you have stated in your question. Whilst this method is a little more tricky to setup initially (keep at it until it works). It will be a lot easier to maintain and work with in the long run.

另一个选择是使用诸如此类的软件包在Django级别处理子域。作为 Django子域(我过去曾经使用过该子域,并发现它是我的首选选项(就处理Django代码中的子域而言)。
无需赘述,nginx将捕获子域并将其全部路由到django。 Django然后将在中间件级别处理子域。

The other option is to handle the subdomains at the django level using a package such as Django Subdomains (I have used this one in the past and found it to be my preferred option (in terms of handling subdomains within django code)). Without going into too much detail nginx will capture the subdomains and route all of it to django. Django will then handle the subdomains at the middleware level.

我个人会使用选项1。选项2是如果您要在不同域上使用不同的应用程序,例如: blog.local.host support.local.host

Personally I would use option 1 for your usage. Option 2 is if you want different apps on different domains for example: blog.local.host, support.local.host.

这篇关于在Django中使用子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆