Separation of Admin Section on a different port in Laravel 5.x
Imported from https://medium.com/@stahiralijan/separation-of-admin-section-on-a-different-port-in-laravel-5-x-975455264954
I was working on a project where client wanted to have admin area on a separate port for privacy reasons.
I consulted old friend Google and searched for the any existing implementations. To my dismay, none of the solutions worked for me.
I then thought about the problem and opened RuoteServiceProvider
in app\Providers
directory in my project.
After a detailed inspection of the file, it hit me.
There is a map()
method in this class (RouteServiceProvider
) with the following code:
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
}
It means you can add your custom routes to it based on condition, so I quickly changed the implementation to the following:
public function map()
{
switch(request()->getPort())
{
case 80:
case 8080:
case 443:
$this->mapApiRoutes();
$this->mapWebRoutes();
break;
// choose a port that is not used by another server
case 8975:
$this->mapAdminWebRoutes();
break;
}
}
Notice I’m scanning port number now for every request, that will have it’s own implications and a small over-head, also, I was unable to add an SSL certificate to this port as HTTPS uses port 443.
Please do comment if you know any technique to add SSL certificate to custom port or if I’m doing something wrong where
Now I added the following method maprAdminWebRoutes
to RouteServiceProvider
class:
protected function mapAdminWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/admin-web.php'));
}
Then I added admin-web.php
file to the routes
directory and added my routes to the file.
We not done yet!
In order for this to work, we also need to add port number to our nginx sites-enabled/YOUR-DOMAIN-CONF-FILE.conf
file:
server {
listen 8975;
server_name YOUR_DOMAIN_NAME;
root '/path/to/your/application/public/;
...
And that’s pretty much it.
Now you can access your custom routes on your custom port(s).
I hope you enjoyed this as much as I did when I implemented this.
Like always, happy coding!