为啥 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;
}
1
kfll 2016-12-06 20:59:19 +08:00
$app->get('/hello/', function ($request, $response, $args) { $response->write('hello'); return $response; });
|
2
millson 2016-12-06 21:05:12 +08:00
|
3
Tuisku 2016-12-06 21:10:06 +08:00 via Android 1
题外话,咱商量个事儿,以后要举例子用 example.com 可以吗。 xxx.com 这种显而易见能打开而且打开之后挺尴尬的域名,有碍风化( ・᷄-・᷅ )
|
4
skyboy OP 按他文档中的写法,加了下面的代码,可以实现自动去掉最后的 /了,但是有一个问题,当响应返回一个字符串时,这个字符串也会被截掉最后一位,显示在页面上。用 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); }); |