【问题标题】:How to use dynamic root path in nginx based on $uri?如何在基于 $uri 的 nginx 中使用动态根路径?
【发布时间】:2016-09-24 11:54:53
【问题描述】:

我在一台服务器上托管多个 django 应用程序。

用户访问时:http://dev-app.example.com/testapp1

我需要使用从 $uri 动态生成的根路径来提供 /static,因为我没有在应用程序中使用相同的资产,而是使用相同的路径。

我的 nginx 配置文件树:

nginx
├── sites-enabled
│   ├── myconf
│   myapps/
│   ├── testapp1
│   └── testapp2

我的配置文件:

server {
    listen 8088;
    server_name dev-app.example.com;

    location = favicon.ico { access_log off; log_not_found off; }

    location /static 
        # The line below isn't working even if the $uri has the string I want to concatenate
        root /home/user$uri/current;
    }

    include /etc/nginx/myapps/*;
}

testapp1 文件:

location /testapp1 {
    include uwsgi_params;
    uwsgi_pass unix:/home/user/testapp1/current/testapp1.sock;
}

testapp2 文件:

location /testapp2 {
    include uwsgi_params;
    uwsgi_pass unix:/home/user/testapp2/current/testapp2.sock;
}

我想使用 nginx 内置变量 $uri 相应地为每个请求的应用程序在 myconf 文件中构建 /static 位置的根路径。

当用户打开http://dev-app.example.com/whatever 我想提供这个:

# In the myconf file
location /static {
     root /home/user/whatever/current;
}

【问题讨论】:

  • 你能展示更大的 nginx 配置吗?我不明白这应该如何工作......
  • @GwynBleidD 我刚刚做了,谢谢。
  • 检查是否理解正确,您的应用程序在//yourdomain.com/testapp1//yourdomain.com/testapp2 上提供服务,但对于这两个应用程序,您的静态文件位于//yourdomain.com/static。对吗?
  • @GwynBleidD 是的,静态文件必须在 //yourdomain.com/static 中,这样每个应用程序都可以拥有自己的资产。 /static 将始终是 testapp1 和 testapp2 中的静态文件的位置,但 /static 重定向到的根路径是根据用户的请求相应更改的位置。

标签: django nginx uwsgi


【解决方案1】:

这样不行。

首先,您必须了解 HTTP 请求的工作原理。每个请求,无论是针对您的网站还是针对静态文件,都是独立的,并且有自己的 URL。 Nginx 自身无法将静态文件请求与请求该静态文件的网站的请求配对...

nginx 可能知道的唯一方法是 Referer 标头,该浏览器可以将请求发送到静态文件。这可能包含请求静态文件的 Web 文档的路径,但它也可以为空!它也可以只包含您网站根目录的路径。

此外,浏览器会尝试缓存所有可以缓存的内容,因此如果用户访问 http://example.com/testapp1 并且该站点包含对 http://example.com/static/style.css 的引用,浏览器将缓存它并且根据对 http://example.com/testapp2 的请求,浏览器将不会下载新的 css 文件,但宁愿使用缓存的。

如果您确定您的 Web 客户端将始终发送正确的 Referer 标头并且不会缓存任何静态文件,您可以尝试从 nginx 中的 $http_referer 变量中提取应用程序的路径。

【讨论】:

  • 感谢您的澄清,所以没有办法在一个服务器块中托管多个应用程序?
  • 是的,有!但不是那样的。只需为每个应用程序创建单独的静态路径。检查 django 中的STATIC_URL 设置。
  • 好的,谢谢。实际上,出于某些原因,我需要保留 /static 。我最终使用了子子域(testapp1.dev-app.example.com) - 捕获第一部分(testapp1),然后在 nginx conf 中使用 if 语句。
【解决方案2】:

在每个服务器块内设置静态位置

server {
  listen 80;

  server_name pool.simlabdevelopments.com; 
  root /srv/http/simlabdevelopments.com;

  location /static/ {
    alias   /srv/webapps/autopool/static/;
  }
}

【讨论】:

  • 我只有一个服务器块,我想根据 $uri 使别名/根动态。
猜你喜欢
  • 2018-07-22
  • 2022-12-14
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 2014-09-07
  • 2021-12-27
  • 2013-01-19
相关资源
最近更新 更多