如何在基于 $uri 的 nginx 中使用动态根路径?

How to use dynamic root path in nginx based on $uri?

我在一台服务器上托管多个 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;
}

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

server {
  listen 80;

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

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

那样不行。

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

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

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

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