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

时间:2018-08-14 03:09:39

标签: php laravel nginx laravel-5

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

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

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

在Google搜索了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将所有无法识别的网址重定向到默认主页吗?

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

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

1 个答案:

答案 0 :(得分: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服务器。

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