在Apache/WSGI下Django URL解析无法工作
当我用Django自带的服务器运行我的应用时,一切都正常。但是当我尝试通过Apache和WSGI运行时,网址却不再被识别,尽管它在urls.py文件里。
我看到的错误页面是这样的:
Page not found (404)
Request Method: GET
Request URL: http://localhost/project/app/live/
Using the URLconf defined in project.urls, Django tried these URL patterns, in this order:
^media/(?P<path>.*)$
^app/live/
The current URL, app/live/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
如你所见,网址(app/live/)在顶层urls.py文件的URL模式里确实存在。而且在Apache的错误日志文件(errors.log)里也没有任何错误。
我的urls.py文件是:
from django.conf.urls.defaults import *
from django.conf import settings
urlpatterns = patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': settings.MEDIA_ROOT }),
(r'^app/live/', include('project.app.urls', app_name='live')),
)
我的WSGI文件是:
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../..')
os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings"
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
最后是我的Apache配置:
WSGIDaemonProcess project processes=2 maximum-requests=500 threads=1
WSGIProcessGroup project
WSGIScriptReloading On
WSGIScriptAlias /project /home/user/project/apache/project.wsgi
编辑:
在RegexURLResolver里加了一些调试输出后,我发现它尝试解析两个网址:app/live/
和project/app/live/
。
所以我把我的urls.py文件改成了这样:
from django.conf.urls.defaults import *
from django.conf import settings
urlpatterns = patterns('',
(r'^app/live/', include('project.app.urls', app_name='live')),
(r'^project/app/live/', include('project.app.urls', app_name='live')),
)
现在可以正常工作了。
4 个回答
1
解决方案1,修改你的Apache配置:
WSGIScriptAlias / /home/user/project/apache/project.wsgi
解决方案2,修改你的urls.py文件:
from django.conf.urls.defaults import *
from django.conf import settings
urlpatterns = patterns('',
(r'^/project/media/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': settings.MEDIA_ROOT }),
(r'^/project/app/live/', include('project.app.urls', app_name='live')),
)
另外,如果你使用的是Apache,可能不想通过Django来提供静态内容:
Alias /media /path/to/media/root
<Location /media>
SetHandle None
</Location>
1
在你的Apache配置中,为你的URL路径前缀添加一个结尾的斜杠:
WSGIScriptAlias /project/ /home/user/project/apache/project.wsgi
2
去掉 WSGIScriptAlias /django
后面的斜杠对我有效