Laravel route of Route::get(".well-known/acme ..." not served from public directory. How can I serve this route from public directory using Laravel?
To serve a Laravel route that is not located in the public directory, you can use Laravel's middleware to handle the request and serve the file from the public directory. In your case, you want to serve the .well-known/acme-challenge
route from the public directory for Let's Encrypt SSL certification.
First, you need to place the files for the Let's Encrypt challenge in the public directory. Create a new directory named .well-known
inside the public
directory. Then, place the files for the Let's Encrypt challenge (e.g., acme-challenge.txt
and the corresponding validation files) inside the .well-known
directory.
Next, create a new middleware to serve the .well-known
route from the public directory. You can create a new middleware using the make:middleware
Artisan command:
php artisan make:middleware ServeWellKnown
Now, open the newly created app/Http/Middleware/ServeWellKnown.php
file and add the following code:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ServeWellKnown
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if ($request->is('*.well-known/*')) {
$path = __DIR__.'/../../public/'.str_replace('/', '/', $request->path());
if (file_exists($path)) {
return response()->file($path);
}
}
return $next($request);
}
}
This middleware checks if the incoming request is for the .well-known
route and serves the file from the public directory if it exists.
Finally, register the middleware in the app/Http/Kernel.php
file by adding it to the $routeMiddleware
array and the $middlewareGroups
array:
protected $routeMiddleware = [
// ...
'serve.well-known' => \App\Http\Middleware\ServeWellKnown::class,
];
protected $middlewareGroups = [
// ...
'web' => [
// ...
\App\Http\Middleware\ServeWellKnown::class,
],
];
Now, define the .well-known
route in your routes/web.php
file and apply the serve.well-known
middleware to it:
Route::get('{domain}/.well-known/{file}', function ($domain, $file) {
return response()->file(public_path("{$domain}/.well-known/{$file}"));
})->where('domain', '([A-Za-z0-9\-]+)')->middleware('serve.well-known');
Replace {domain}
with the actual domain name.
Now, the .well-known
route should be served from the public directory using the Laravel middleware.