php - Laravel + AngularJS Nginx 路由

标签 php angularjs laravel nginx laravel-5.3

我有以下问题, 我需要配置 Nginx,因此在用户访问任何 URL 时,它将保留 uri(例如 domain.com/some/url/),但仅传递给 laravel /并让 Angular 处理路由。

Route::get('/', function(){
   return view('index');
});

当访问 /api/{anything} 时,Laravel 将启动。

现在我从公共(public)文件夹返回 index.html 直到找到解决方案 这是我的配置:

location / {
    index index.html;
    try_files $uri $uri/ /index.html;
}
location /api {
    index index.php;
    try_files $uri $uri/ /index.php?$query_string;
}

我知道我可以制作如下路线:

Route::get('{anything?}', function(){
    return view('index');
});

但是太宽泛了。

更新:

location / {
    rewrite ^/(.*)$ / break;
    index index.php;
    try_files $uri $uri/ /index.php;
}
location /api {
    index index.php;
    try_files $uri $uri/ /index.php?$query_string;
}

最佳答案

您无法通过简单的重写来实现您的目标。 Laravel 始终知道真实的 URI

关键是你需要用一个路由来处理所有的请求。 Laravel 使用 $_SERVER['REQUEST_URI'] 变量进行路由,并从 fastcgi 传递给 Laravel。变量 REQUEST_URI 在 nginx 的 $request_uri 变量的 fastcgi_params 文件中设置:

fastcgi_param  REQUEST_URI        $request_uri;

所以你需要将 REQUEST_URI 作为 / 传递给 Laravel 来处理请求 /bla/bla 因为它是 /.

只需在您的配置中添加一行:

location ~ \.php$ {
    # now you have smth like this
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi_params;

    # add the following line right after fastcgi_params to rewrite value of the variable
    fastcgi_param  REQUEST_URI       /;
}

如果您也有 /api/,则需要对该行进行一些编辑:

set $request_url $request_uri;
if ($request_uri !~ ^/api/(.*)$ ) {
    set $request_url /;
}
fastcgi_param  REQUEST_URI $request_url;

Nginx 警告说 if 是邪恶的,这只是第一个想法。

总结:

/ 转到 Laravel / 路由。

/api/* 转到 Laravel api 路由。

另一个请求转到 Laravel / 路由。

关于php - Laravel + AngularJS Nginx 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41859481/

相关文章:

php - PHP 中可以将字符串转换为类名

json - angularjs向json数据添加一列

php - laravel post 500(内部服务器错误)?

当我访问对象/数组的未定义属性时,php 不会抛出错误,而只是发出通知

php - 打开替代方案

php - 使用 MySqli 和数组返回多行

javascript - 函数和闭包可以替代 Javascript 中的类吗?

html - 输入以 Angular 聚焦时的焦点标签

laravel - 如何设置 Laravel Cashier 的默认货币

php - 如何在 Laravel/Eloquent 中为多态表添加别名