Nginx 总是将 Laravel 路由重定向到默认的根 index.php 页面

Posted

技术标签:

【中文标题】Nginx 总是将 Laravel 路由重定向到默认的根 index.php 页面【英文标题】:Nginx always redirect Laravel routes to default root index.php page 【发布时间】:2019-01-20 19:46:15 【问题描述】:

我是 Laravel 新手。在我的 Mac (macOS 10.13) 上,我配置了 nginxphpmysql 环境。首先,Nginx localhost:8080/laravel/public 显示 laravel 欢迎页面没有任何问题。但是当我尝试添加自定义路由时,例如:

Route::get('test', function () 
    return 'Hello World!';
);

我在 localhost:8080/laravel/public/test 上得到了 404 页面。

在谷歌搜索路由 404 问题的解决方案后,我通过添加修改了我的 nginx conf 文件

try_files $uri $uri/ /index.php?$query_string

如下:

server 
    ...

    location / 
        try_files $uri $uri/ /index.php?$query_string;
    

    location ~ \.php$ 
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    

现在是故事,404 问题已得到解决。但我仍然无法访问正确的路线页面。

当我再次打开 localhost:8080/laravel/public/test 时,浏览器将我带到 nginx docroot 页面(即 localhost:8080/index.php)。

我已经在我的 laravel 主文件夹中尝试了 php artisan serve,使用该命令 localhost:8000/test 可以通过“Hello World!”正确访问文本。

更新:

我只是在 localhost:8080/ 之后尝试了一些其他字符串,例如 localhost:8080/abc 什么的,似乎任何子路径都会将我带到 localhost:8080/index.php 页面!在 try_files $uri $uri/ /index.php?$query_string 添加之后。如果我删除这行代码,localhost:8080/abc 将显示 404 页面(这应该是正确的,因为我的根文件夹中没有 abc.php 文件)。

好像加了之后

location / 
    try_files $uri $uri/ /index.php?$query_string;

Nginx 将它无法识别的所有 url 重定向到默认主页?

有人能告诉我为什么我的 Nginx 在添加 try_files $uri $uri/ /index.php?$query_string 后无法使用 Laravel 路由吗?

如果您需要更多详细信息,请告诉我。非常感谢!

【问题讨论】:

仅供小费 - 使用 Laravel Valet。 laravel.com/docs/5.7/valet 在开发过程中对很多事情都有帮助。 您在 .env 中的 APP_URL 值是多少? @alariva APP_URL=localhost @imrealashu 感谢您的快速评论,我知道有很多更简单的方法可以设置开发环境,但只是好奇为什么我会遇到这样的问题。 XD @alariva 我刚刚将值更改为 localhost:8080 但localhost:8080/laravel/public/test 现在显示“找不到文件”。 【参考方案1】:

嗯.. 我通过修改我的 Nginx 站点配置文件解决了这个问题,改变了

server 

    ...

    root         /var/www;

    location / 
        try_files $uri $uri/ /index.php?$query_string;
    

    location ~ \.php$ 
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    

server 

    ...

    root         /var/www/laravel/public;

    location / 
        try_files $uri $uri/ /index.php?$query_string;
    

    location ~ \.php$ 
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    

是的,只需将根路径更改为 laravel 的公用文件夹,然后重新启动 nginx 服务器。

现在我在http://localhost:8008/test 上获得了Hello World!

【讨论】:

以上是关于Nginx 总是将 Laravel 路由重定向到默认的根 index.php 页面的主要内容,如果未能解决你的问题,请参考以下文章

如何使用获取参数将 laravel (5.3) 路由重定向到其他路由

Laravel 5 中间件身份验证总是失败并重定向到登录

Laravel 8 Jetstream如何在重置密码后将用户重定向到自定义路由

使用自定义中间件会将我重定向到 /home,即使 Laravel 中的中间件是空的

如何将没有参数的 Laravel 路由重定向到具有默认参数的控制器方法?

如果路由不在子域中,Laravel 子域路由重定向到 404