Recently at HighSolutions we have had a small project from our client where we were asked to polish up the design and enhance the API for their React-based Calculator web application. We’re big fans of Laravel, so we decided to replace the poorly written API with fast and maintainable API in Lumen.
The only problem here was the fact that we did not have access reaching beyond public_html, so we were forced to insert Lumen in the public catalog.
Thus the structure of folders looks like this:
We also wanted to maintain all routes to API from the old system, so we were forced to put Lumen in api folder.
Specification of routes looks the following way:
GET api/categories.php Return JSON with list of categories and nested subcategories POST api/user.php Return JSON with authentication result
So to make it work, we had to:
- Firstly, direct all traffic going to http://react-project.dev/api/ to /api/public/index.php file, which can be done by .htaccess in api folder.
- First, we set RewriteBase to /api so, every request will be going there, not to main domain.
- Second rule is required to redirect every request to public/index.php.
- Especially when we are doing this for the purpose of the last rule to redirect all traffic that is not getting to public catalog to this particular one.
- This is very similar to standard .htaccess for Laravel. The only difference is RewriteBase, once again set to /api, because we are in subfolder of main domain.
What we should do when we want to use Lumen API inside Laravel app?
Sometimes we might need to have a dedicated API outside Laravel, but also in /api/ folder. How to do this? With our .htaccess files it’s very simple.
We need three .htaccess on three different levels:
- First basic .htaccess is for Laravel:
- This is standard Laravel’s 5.4 .htaccess and we don’t need to do anything here. We don’t need to redirect API neither, because this will be handled by next .htaccess files.
- Second .htaccess is for api catalog inside public catalog of Laravel
- It’s just as explained in the first part of the article.
- Last .htaccess is inside api/public and it’s the same as the first one:
The last thing to do is to wrap all routes in Route::group with prefix="api":
And it’s working.
You just need to remember that in Laravel app you cannot specify routes in /api/. We recommend to write comment in api.php and to remember this:
Of course you need to remember to restrict access to all vulnerable assets like .env files and config files. If you can hide applications files under public catalog, do it.
You can also have API under domain catalog, when you use subdomain e.g. https://api.react-project.dev. We recommend this option, but if it is not possible, you know what to do.
If you have better ideas, don’t hesitate to share it with us.