Abhishek
Abhishek

Reputation: 159

How to solve 404 error after deploying laravel in server under subfolder?

I have uploaded a laravel project in server inside a subfolder under public_html directory. For example www.xyz.com/subfolder. Bot I am getting error 404 NOT Found.

My htaccess code

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^public
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

Upvotes: 1

Views: 2075

Answers (2)

hassan
hassan

Reputation: 8288

While @Asif khan's answer doing the required job, it is still hard to keep in mind adding the same prefix for every new route you are going to add to your application. Also, what about the API's file routes? And the other route files you are going to add to your application?

As an alternative, you can add the prefix within your RouteServiceProvider

public function boot(): void
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });

    $this->routes(function () {
        Route::prefix('YOUR GLOBAL PREFIX')->group(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('api')
                ->prefix('api/v1')
                ->name('api.v1.')
                ->group(base_path('routes/api-v1.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    });
}

This way, you will keep your routes files as clean as possible, also you will do it once and forever.

Upvotes: 0

Aasif khan
Aasif khan

Reputation: 171

So, I've been fiddling a lot with VirtualHost(s), but the best solution I found does not involve them at all, and here it is.

First thing to do is to configure .htaccess files for both the app's root folder and its public folder. I found a simple working .htaccess file in this answer, which I report here:

<IfModule mod_rewrite.c>
    RewriteEngine On 
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

The default .htaccess works fine, instead, for the public folder.

The last step is to correctly configure your routes in routes.php. The workaround which works for me is quite rough, and maybe one could find some more refined solution, but still here it is.

// Get base (root) route
$base_route = basename(base_path());

Route::get($base_route, function () {
    return view('welcome');
});

Route::get($base_route.'/myRoute', function() {
    return view('myRoute');
});

So basically you need to prepend $base_route to every route in your app.

Upvotes: 2

Related Questions