Laravel + AngularJS Nginx路由 [英] Laravel + AngularJS Nginx routing

查看:91
本文介绍了Laravel + AngularJS Nginx路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following issue, I need to configure Nginx, so on any URL user accesses, it will keep the uri (example domain.com/some/url/), but pass to laravel only / and let Angular handle the routing.

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

当访问/api/{anything}时,Laravel会加入.

And when accessing /api/{anything} Laravel will kick in.

现在,我从公用文件夹返回index.html,直到找到解决方案为止 这是我的配置:

For now I return index.html from public folder until I find solution Here is My Config:

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

我知道我可以进行以下路线:

I know I can make a route like:

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.

You can't achieve you goal with simple rewrite. Laravel always knows about the real URI.

关键是您只需要处理一条路由即可处理所有请求. Laravel使用$_SERVER['REQUEST_URI']变量进行路由,并将其从fastcgi传递给Laravel.变量REQUEST_URI是通过nginx的$request_uri变量在fastcgi_params文件中设置的:

The key point is that you need to handle all requests with just one route. Laravel uses $_SERVER['REQUEST_URI'] variable to route and it is passed to Laravel from fastcgi. The variable REQUEST_URI is set in fastcgi_params file from nginx's $request_uri variable:

fastcgi_param  REQUEST_URI        $request_uri;

因此,您需要将REQUEST_URI作为/传递给Laravel以处理请求/bla/bla,因为它是/.

So you need to pass REQUEST_URI as / to Laravel to handle request /bla/bla as it is /.

只需在配置中添加一行:

Just add one line to your config:

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/,则需要对该行进行一些

If you have /api/ as well, you need some edits for the line:

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

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

Nginx warns that if is an evil, that's just a first idea.

总结:

/转到Laravel /路线.

/ goes to Laravel / route.

/api/*转到Laravel API路线.

/api/* go to Laravel api routes.

另一个请求转到Laravel /路线.

Another requests go to Laravel / route.

这篇关于Laravel + AngularJS Nginx路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆