Redirect Url Issue with Laravel and htaccess

Viewed 1920

I create virtual host for my project in local xampp. Url: http://kooltech-us.com/

I have folder's name admin (From picture below ) in public folder (Laravel) .

enter image description here

in my project my admin login url http://localhost/admin/login .

I hit url http://localhost/admin/login to go to admin login page .. it's okay.. but when i hit this http://localhost/admin . it takes me to the public/admin folder . That means show me public Directory listing.

enter image description here

For prevent access Directory listing or public/admin I write in Options - Indexes code in .htaccess file .it's give me 403 Error ( Access forbidden! ) in general. it's work.

enter image description here

I looking for that when I hit the url http://localhost/admin it will take me to http://localhost/admin/login .

Note:

  1. I did not change folder structure. (Laravel Default Folder Structure Exist).
  2. Only one line code I write in .htacees file : Options - Indexes . that give me 403 Error ( Access forbidden! ) in general.
  3. Version "laravel/framework": "5.8.*"

I write in web.php but it's not working ..

Route::get('/admin', function () {
  return redirect('/admin/login');
});

if need more explanation please comment..

1 Answers

To modify the .htaccess you would need to add something like this to your .htaccess This will redirect all request from /admin to /public but still show as /admin which will allow your redirect in web.php to work:-

RewriteRule admin /public [L] 

Which would give you:-

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On
    
    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule admin /public [L] 
    RewriteRule ^ index.php [L]

    
</IfModule>

However I still feel that this is bad practice, and changing your directory strcture as @flakerimi sugested would be a much better solution.

Related