关于 laravel 的路由解析问题

2017-12-29 13:53:58 +08:00
 waibunleung
情况是这样的,刚安装了 laravel,然后用 nginx 配置了 url 的重写
#location / {
# index index.php index.html index.htm;
# try_files $uri $uri/ /index.php?$query_string;
#}
然后配置了 laravel 的路由:
Route::get('/ex/am',function(){
return 'hello laravel';
});
此时输入 http://localhost/ex/am 是显示 hello laravel 的
然后我把 nginx 的重写注释掉,在浏览器输入:
http://localhost/index.php/ex/am 显示 not found
http://localhost/inde.php?/ex/am 也是 not found
重新开启 nginx 重写后又能正常访问

所以,我想知道为什么不开启重写,直接访问以上两个地址之一没法正常显示 hello laravel ??
试过看源码,有点绕。。。所以来这边问一下
3870 次点击
所在节点    PHP
11 条回复
sunflyer
2017-12-29 14:16:13 +08:00
/ex/am =》这部分叫 uri
/ex/am?a=123&b=456 =>问号后面的叫 query_string
emm,剩下的应该不用说了
printempw
2017-12-29 14:33:24 +08:00
你的意思是开启 Nginx URL 重写后 /index.php/ex/am 可以正常访问吗?你的请求确定经过 Laravel 了吗?提示的 Not found 是 Laravel 报的错还是 Nginx 报的错?

稍微看了一下源码(人在外面),Laravel 从 REQUEST_URI 后似乎没有对 index.php 这类 script name 做特殊处理。所以你访问的 /index.php/ex/am 与你定义的路由 /ex/am 应该是**不匹配**的(没验证过,不一定对,手机看源码太痛苦了)

https://github.com/laravel/framework/blob/5.5/src/Illuminate/Routing/Matching/UriValidator.php
my101du
2017-12-29 14:39:26 +08:00
未开启重写,末尾加斜杠。会被 nginx 去找匹配的子目录吧。
kismetX
2017-12-29 14:39:52 +08:00
你的 nginx 配置有问题吧,就单 http://localhost/能访问吗?
waibunleung
2017-12-30 15:21:38 +08:00
@my101du 我没有末尾加斜杠啊
waibunleung
2017-12-30 15:24:03 +08:00
@kismetX 关于 网址是 localhost 只是用于方便提问的网址书写,我自己配的 nginx 本地网址是“ w w w .lab.com ”,请不要纠结 localhost 的问题
waibunleung
2017-12-30 16:29:53 +08:00
@printempw 你这么一说,是 nginx 报的 404 错误,请求应该没走 laravel,可是为什么 http://localhost/index.php?/ex/am 或者 http://localhost/index.php?/ex/am
这样的请求没有走 laravel 的路由?已经进入入口文件了,路由却没有解析到

另外,根据以上 nginx 的配置,这个 url: http://localhost/ex/am 重写之后真实访问的 url 是怎样的?
waibunleung
2017-12-30 16:30:51 +08:00
@my101du 我的意思是我没有开启重写,就不会匹配到斜杠那一项吧?
waibunleung
2017-12-30 16:44:33 +08:00
@printempw 开启 Nginx URL 重写后 /index.php/ex/am 确实可以正常访问
medz
2018-01-02 17:58:45 +08:00
@waibunleung 很简单,Laravel 现在是采用 pathinfo 模式的,也就是通过请求路径进行分析路由,你可以开启重写后在 index.php 打印 $_SERVER 你再关闭后打印,你看 `REQUEST_URI` 部分是不一样的。
waibunleung
2018-01-03 17:25:12 +08:00
@medz
重写前后,我看到的 REQUEST_URI 是一样的。。。。不知道你有没有试验过

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

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

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

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

© 2021 V2EX