路由最后的/问题

2016-12-06 19:14:22 +08:00
 skyboy

为啥 slim 这个路由 http://www.xxx.com/hello 注册后,当网址最后面加一个下划线, http://www.xxx.com/hello/ 就显示 404 了,怎么让路由注册后,无论最后加不加 /,都能响应一个路由请求呢。

$app->get('/hello', function ($request, $response, $args) { $response->write('hello'); return $response; });

Nginx 配置如下:

server { listen 80; listen [::]:80;

    server_name www.xxx.com xxx.com;

   # root /var/www/www.xxx.com;

    root /slim3/website/ ;
    index  index.php index.html;

    location / {
           # try_files $uri $uri/ =404;
          # try_files $uri /index.php;
        try_files $uri $uri/ /index.php$is_args$args;

    }

    location ~ \.php$ {

            include snippets/fastcgi-php.conf;

            # With php7.0-cgi alone:
            # fastcgi_pass 127.0.0.1:9000;
            # With php7.0-fpm:
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

   #access_log  /var/www/www.xxx.com.log;

}

1165 次点击
所在节点    问与答
4 条回复
kfll
2016-12-06 20:59:19 +08:00
$app->get('/hello/', function ($request, $response, $args) { $response->write('hello'); return $response; });
millson
2016-12-06 21:05:12 +08:00
Tuisku
2016-12-06 21:10:06 +08:00
题外话,咱商量个事儿,以后要举例子用 example.com 可以吗。 xxx.com 这种显而易见能打开而且打开之后挺尴尬的域名,有碍风化( ・᷄-・᷅ )
skyboy
2016-12-07 16:15:09 +08:00
按他文档中的写法,加了下面的代码,可以实现自动去掉最后的 /了,但是有一个问题,当响应返回一个字符串时,这个字符串也会被截掉最后一位,显示在页面上。用 echo "hello"也一样,只能显示 htll,这个问题可怎么办呢。大侠。

use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

$app->add(function (Request $request, Response $response, callable $next) {
$uri = $request->getUri();
$path = $uri->getPath();
if ($path != '/' && substr($path, -1) == '/') {
// permanently redirect paths with a trailing slash
// to their non-trailing counterpart
$uri = $uri->withPath(substr($path, 0, -1));

if($request->getMethod() == 'GET') {
return $response->withRedirect((string)$uri, 301);
}
else {
return $next($request->withUri($uri), $response);
}
}

return $next($request, $response);
});

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/325740

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX