II'm using Laravel and have a folder of uploaded files in my public directory called uploads.
I want to make sure that no one can accidentally navigate to the root of that directory, so I've added a route as follows:
Route::get('uploads', function(){
return Redirect::to('/');
});
This isn't working as I'm getting a redirect loop error in my browsers. I've narrowed this down to being the fact that the directory exists - if I remove / rename the directory, the route works as expected.
That makes me think there's a better way to handle this. How do I fix this problem?
Apparently the redirect loop seems to come from trailing slash redirection, defined in Laravel default .htaccess file. Removing following line:
RewriteRule ^(.*)/$ $1 [L,R=301]
will fix the problem with redirect loop on folders residing in public folder.
This however takes you one step back, because now you do not have trailing slash redirection.
Insted what you can do is redirect trailing slashes only if not an existing directory, like this:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ $1 [L,R=301]
Second thing you probably want to do is remove the same condition from the last block of Laravel default .htaccess file:
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
This block is saying: "Redirect everything to index.php file, except existing files and folders." I commented out the directory condition, because I do not want people to access folder index in my public folder. If you do, uncomment it.
This is my complete .htaccess file:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteBase /
# Redirect trailing slashes
# Only if not existing directory. This prevents redirect loop.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ $1 [L,R=301]
# Redirect everything to index.php if not existing file like css or jpg
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With