V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
skyboy
V2EX  ›  问与答

路由最后的/问题

  •  
  •   skyboy · 2016-12-06 19:14:22 +08:00 · 1162 次点击
    这是一个创建于 2690 天前的主题,其中的信息可能已经有所发展或是发生改变。

    为啥 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;
    

    }

    4 条回复    2016-12-07 16:15:09 +08:00
    kfll
        1
    kfll  
       2016-12-06 20:59:19 +08:00
    $app->get('/hello/', function ($request, $response, $args) { $response->write('hello'); return $response; });
    millson
        2
    millson  
       2016-12-06 21:05:12 +08:00
    Tuisku
        3
    Tuisku  
       2016-12-06 21:10:06 +08:00 via Android   ❤️ 1
    题外话,咱商量个事儿,以后要举例子用 example.com 可以吗。 xxx.com 这种显而易见能打开而且打开之后挺尴尬的域名,有碍风化( ・᷄-・᷅ )
    skyboy
        4
    skyboy  
    OP
       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);
    });
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   988 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 22:11 · PVG 06:11 · LAX 15:11 · JFK 18:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.