Laravel + AngularJS Nginx Routing

I have the following problem, I need to configure Nginx, so with any access to the URL, it will save uri (example domain.com/some/url/ ), but will only go to laravel / and let Angular handle the routing.

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

And when accessing /api/{anything} Laravel will start.

Now I am returning index.html from the public folder until I find a solution. Here is My Configuration:

 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 that I can make such a route as:

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

But for the broad.

Update:

 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; } 
+5
source share
1 answer

You cannot achieve your goal by simply rewriting. Laravel always knows about the real URI .

The key point is that you need to process all requests with only one route. Laravel uses the variable $_SERVER['REQUEST_URI'] for routing and is passed to Laravel from fastcgi . The REQUEST_URI variable is set in the fastcgi_params file from the nginx $request_uri variable:

 fastcgi_param REQUEST_URI $request_uri; 

Therefore, you need to pass REQUEST_URI as / in Laravel to handle the request /bla/bla , since this is / .

Just add one line to the configuration:

 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 /; } 

If you have /api/ , you need some changes for the line:

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

Nginx warns that if is evil, this is just the first idea.

Summarizing:

/ goes to the Laravel route / .

/api/* go to Laravel route routes.

Other requests go to the Laravel / route.

+4
source

Source: https://habr.com/ru/post/1263349/


All Articles