【发布时间】:2013-04-15 18:48:15
【问题描述】:
我正在尝试在 Django 的 localhost 网络服务器 (127.0.0.1:8000) 前使用 Nginx 来提供静态内容。我希望 Nginx 为“/static”下的所有文件提供服务,如果没有,则将请求传递到 Django 的网络服务器,但我被卡住了!这是我所做的:
- 让 Nginx 在我的 OSX 上运行,所以“欢迎使用 Nginx!”页面显示在本地主机上。
-
更改了我的 /etc/hosts 文件以添加“testdev.com”:
127.0.0.1 本地主机
127.0.0.1 testdev.com
在 /usr/local/src/nginx-1.2.6 中创建 /sites-available 和 /sites-enabled 文件
-
我的/conf中的nginx.conf文件是默认加上include语句:
包括 /usr/local/src/nginx.1.2.6/sites-enabled/testdev.com
5.我的 testdev.com 文件在 sites-available 中,在 /sites-enabled 中有一个符号链接。
server {
root /<path-to-my-django-project>/website/static;
server_name testdev.com;
gzip off;
listen 8000;
location = /favicon.ico {
rewrite "/favicon.ico" /img/favicon.ico;
}
proxy_set_header Host $host;
location / {
if (-f $request_filename) {
add_header X-Static hit;
access_log off;
}
if (!-f $request_filename) {
proxy_pass http://127.0.0.1:8000;
add_header X-Static miss;
}
}
}
如果我 curl testdev.com,它会显示 Nginx:
curl -I http://testdev.com
HTTP/1.1 200 OK
Server: nginx/1.2.6
Date: Mon, 22 Apr 2013 18:37:30 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Sun, 21 Apr 2013 19:39:47 GMT
Connection: keep-alive
Accept-Ranges: bytes
但是如果我尝试访问静态文件,什么都没有:
curl -I http://testdev.com/static/css/style.css
HTTP/1.1 404 Not Found
Server: nginx/1.2.6
Date: Mon, 22 Apr 2013 18:38:53 GMT
Content-Type: text/html
Content-Length: 168
Connection: keep-alive
所有这些都基于谷歌搜索,并找到this。
我在里面加了
listen 8000
我的 testdev.com conf 文件中的语句,因为我认为 Nginx 虚拟主机需要它,但我非常困惑。博客作者使用了
127.0.1.1 testdev.com
在他的主机文件中,但如果我添加它,第一个 curl 语句就会挂起。
我做错了什么?
【问题讨论】:
-
@Evgeny - 怎么样,这不是生产部署问题吗?我在本地主机中。
-
@professorDante - 我要去第二个 Evgeny。尽管这是一个生产问题,但它仍然是相同的根本原因。你所要求的不能真正做到。 Django 的网络服务器仅在您的 settings.py 中有“DEBUG=True”时运行。您无法在 nginx 和 django 网络服务器中进行设置,因为 django 网络服务器仅在调试打开时运行。
-
nginx 不关心它的生产环境还是本地主机,提供静态文件的配置是相同的。只需从重复问题的答案中复制粘贴即可。