(Symfony2 + nginx)根据请求目录

时间:2017-04-21 18:20:48

标签: php symfony nginx load-balancing

我一直在寻找答案,并没有找到任何可以帮助我解决我的具体情况。我是nginx的新手,所以我还是习惯了。

我有一个Symfony应用程序在两个安装了php-fpm的Web服务器上运行。主服务器具有nginxphp-fpm,而第二个服务器只有php-fpm。我希望所有到/admin/*的路由都通过main_server上游和其他非/admin/*的路由路由到上游的default_balancer

我尝试了各种各样的事情但无济于事。我希望所有路由仍由app.php处理(静态资产除外)我只希望上游服务器根据请求URL是否为/admin/*而更改。

主服务器URL示例(将始终转到main_server,如果main_server不可用而不是默认为其他服务器,则最好抛出错误:

  • /app.php/admin
  • /app.php/admin
  • /app.php/admin /
  • /app.php/admin/login
  • /app.php/admin/user/delete

默认平衡器网址示例(将始终转到default_balancer):

  • /app.php /
  • /app.php/contact-us
  • /app.php/store

仅供参考:上述网址是在没有/app.php部分的情况下输入浏览器的,但是由于try_files部分

而在内部以这种方式处理

这是我的nginx配置文件(排除了不重要的位)。

upstream default_balancer {
    server 192.168.1.1:9000 weight=5; # main server
    server 192.168.1.2:9000 weight=3 max_fails=3 fail_timeout=30s; # second server
}

upstream main_server {
    server 192.168.1.1:9000; # main server
}

server {
    listen      80;
    server_name example.local;
    rewrite     ^   https://$server_name$request_uri? permanent;
}

server {
    listen 443;
    server_name example.local;
    root /var/www/vhosts/symfony/web;

    [...]

    location / {
        # try to serve file directly, fallback to app.php
        try_files $uri /app.php$is_args$args;
    }

    location ~ ^/app\.php(/|$) {
        fastcgi_pass default_balancer;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        # When you are using symlinks to link the document root to the
        # current version of your application, you should pass the real
        # application path instead of the path to the symlink to PHP
        # FPM.
        # Otherwise, PHP's OPcache may not properly detect changes to
        # your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
        # for more information).
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/app.php/some-path
        # Remove the internal directive to allow URIs like this
        internal;
    }
}

额外信息:我这样做的原因是因为我们的设计师通过网站上的管理面板处理上传图片。因为资产是由主服务器(安装了nginx并提供静态资产)处理的,所以我认为将所有/admin/*路由转发到该单个服务器是最简单的。如果他们有效,我会对其他解决方案持开放态度。

1 个答案:

答案 0 :(得分:4)

您的网址示例与您的配置不符。假设您只想将以/admin开头的URI发送到/app.php,您可以添加此块:

location ^~ /admin {
    fastcgi_pass main_server;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $realpath_root/app.php;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
}

如果您在/admin下也有静态文件,则可能需要稍微复杂一些:

location ^~ /admin {
    try_files $uri @admin;
}
location @admin {
    fastcgi_pass main_server;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $realpath_root/app.php;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
}