使用 symfony3 提供远程静态文件

Serving remote static files with symfony3

我的 Nginx 配置有问题。我有 2 台服务器,一台使用 nginx,一台使用 symfony3 中的 webApp。 这是我的配置:

location /portal/mysite/ {

    set $frontRoot /srv/data/apps/mysite-portal-stag/current/web;
    set $sfApp app.php; # Change to app.php for prod or app_dev.php for dev

    root  /srv/data/apps/mysite-portal-stag/current/web;

    rewrite ^/portal/mysite/(.*)$ / break; 
    try_files $uri @sfFront;

}
location @sfFront {

    root  /srv/data/apps/mysite-portal-stag/current/web;

    fastcgi_pass myserver:myport;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $frontRoot/$sfApp;

    fastcgi_param SCRIPT_NAME /portal/mysite/$sfApp;

}

该网站适用于所有 php 脚本,但所有资产(静态文件)都是损坏的文件。我不太了解 Nginx 如何工作以指示什么是静态文件和 "tell" 我的代理,它们不是脚本。

在有人找到更好的解决方案之前,我已经找到了一个非常丑陋的解决方案,这就是我所做的:

  • 我已经把所有的assets仓库复制过来,复制到我的nginx所在的代理服务器上

这是我的新配置:

location /portal/mysite/ {

    set $frontRoot /srv/data/apps/mysite-portal-stag/current/web;
    set $sfApp app.php; 

    root  /srv/data/apps/mysite-portal-stag/current/web;

    rewrite ^/portal/mysite/(.*)$ / break;
    try_files $uri @sfFront;

}
location /portal/mysite/asset {
    root  /tmp/mysite/asset;
    rewrite ^/portal/mysite/asset/(.*)$ / break;
}
location @sfFront {

    set $frontRootWeb /srv/data/apps/mysite-portal-stag/current/web;
    root  /srv/data/apps/mysite-portal-stag/current/web;

    fastcgi_pass myAdressWeb:myPort;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $frontRoot/$sfApp;

    fastcgi_param SCRIPT_NAME /portal/mysite/$sfApp;

} 

现在可以正常使用了,所有 js/css 和图片都找到了。

如果有人想到 "cleaner" 答案,非常欢迎他回答。

try_files 指令会自动尝试查找静态文件,并在放弃之前将其作为静态文件提供,并让请求作为脚本提供。

  • http://nginx.org/r/try_files

    Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made.

请注意,虽然您已经在使用 try_files,但您的路径处理似乎不符合规范。


至于您自己的临时解决方案 there's nothing wrong with using a rewrite or two,但话虽如此,您似乎会从 alias 指令中受益。

但是,您从未解释过为什么要提供来自 /tmp 的东西。请注意 /tmp 经常被一些 cron scripts, e.g., on OpenBSD, the /etc/daily script would automatically find and remove files older than about 7 days (on a daily basis 自动清除,顾名思义。


总而言之,你应该首先弄清楚文件系统的网络视图和你的文件系统之间的适当映射是什么。

随后,如果找到前缀,只需对资产使用单独的 location,连同 alias

否则,找出 try_files 按预期工作的路径。