首页 > 解决方案 > Symfony 重写 nginx

问题描述

我正在使用 Symfony 3.4 运行,并且我已经将我的 nginx 配置为直接使用http://example.org/my-route而不是http://example.org/app.php/my-route

server {
    location / {
        try_files $uri /app.php$is_args$args;
    }

    location ~ ^/(app_dev|config)\.php(/|$) {
        # bla bla bla
    }

    location ~ ^/app\.php(/|$) {
        # bla bla bla
    }
}

但现在我想将访问我网站的用户重定向到http://example.org/app.php/my-routehttp://example.org/my-route

我尝试创建一个新的重写,但我得到了循环重定向

rewrite ^/app.php(.*) /$1 permanent;

我应该只在我的 app.php 中添加一个 header() 吗?

if (strpos($request->getUri(), $request->getHost().'/app.php') !== false) {
    $uri = str_replace($request->getHost().'/app.php', $request->getHost(), $request->getUri());
    header('Location: ' . $uri, true, 301);
}

标签: symfonynginx

解决方案


为避免循环,您需要识别何时/app.php是原始请求,而不是try_files语句生成的相同 URI。

原始请求可以在$request_uri变量中找到,可以使用if块进行测试。

例如:

if ($request_uri ~ ^/app.php(.+)$) { return 301 $1; }

请参阅此使用注意事项if


推荐阅读