使用場景:html
Django中有兩個app,若是經過域名來訪問,能夠使用www.domain.com/a、www.domain.com/b來訪問。這樣就顯得有點LowB了。若是我想經過a.domain.com、b.domain.com來訪問兩個app怎辦?git
請使用django-host來實現。github
一、安裝django-host 插件web
pip install django-host
二、修改django配置 settings.pydjango
1.在 INSTALLED_APP 中註冊 'django-host' 應用 2.在 MIDDLEWARE 配置項的開始位置,添加 'django_hosts.middleware.HostsRequestMiddleware' 3.在 MIDDLEWARE 配置項的結束位置,加'django_hosts.middleware.HostsRequestMiddleware' 4.在 settings.py 文件同目錄下建立 host.py 文件,添加以下內容: from django_hosts import patterns, host from django.conf import settings from APP1 import views from APP2 import views host_patterns = patterns('', host(r'app1', 'APP1.urls', name='APP1'), host(r'app2', 'APP2.urls', name='APP2'), ) 5.修改 settings.py 文件,在 ROOT_URLCONF 配置項以後增長 ROOT_HOSTCONF = '項目目錄名.host' #注意,不是app的名字 6.修改 settings.py 文件,在ROOT_HOSTCONF 配置項以後增長 DEFAULT_HOST = 'app1' #設置一個默認的域名,在沒有匹配到所請求的域名時,默認返回這個。 7.在每一個app下建立本身的urls.py
因爲線上使用的Nginx+Uwsgi的環境,順便貼一下Nginx和Uwsgi的配置app
Nginx的配置以下:dom
a.domain.com配置socket
server { listen 80; server_name a.domain.com;
location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8000; uwsgi_param UWSGI_SCRIPT web.wsgi; } location /static { alias /data/local/app/app1/static; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; }
b.domain.com配置url
server { listen 80; server_name b.domain.com; #charset koi8-r; access_log logs/app2.access.log main; error_log logs/app2.error.log info; location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8000; uwsgi_param UWSGI_SCRIPT web.wsgi; uwsgi_read_timeout 20; } #location /static { # alias /data/local/app/blog/web/WeChatAPI/static; #} }
Uwsgi的配置以下:spa
[uwsgi] socket = :8000 chdir = /data/local/app/ #module = web.wsgi:app1 wsgi-file = web/wsgi.py master = true processes = 1 pidfile = /tmp/web-master.pid daemonize = /var/log/uwsgi/app1.log
參考:http://blog.csdn.net/sinat_21302587/article/details/74017312
django-hsot github地址:https://github.com/jazzband/django-hosts