8

I've created a Laravel project under mywebsite.com/laravel/. When I go to mywebsite.com/laravel/test, everything is ok, but when I go to mywebsite.com/laravel/test/, I'm redirected to mywebsite.com/test.

I have the files index.php and .htaccess in my /laravel directory. This is my .htaccess file:

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

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteBase /laravel
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

I have no idea why RewriteBase doesn't work. I've tried /laravel, /laravel/ and laravel; nothing worked.

My routes.php file

<?php
Route::get('/test/{name?}', 'MainController@index');

Route::group(['middleware' => ['web']], function () {
    //
});
  • 1
    The code works fine from my tests in every way. Technically, with how you've written the rule, you shouldn't even need the RewriteBase because the rule will include the entire URI and just strip the last /. – Devon Bessemer Dec 23 '15 at 18:27
  • I've tested it on localhost and on hosting server, in both cases it redirects me to domain.com/test, I have no idea what's wrong with it. –  Dec 23 '15 at 18:48
  • @Wolen Please, share your `route.php` – smartrahat Dec 23 '15 at 19:34
  • @Wolen Don't post in answer. Edit your question. At the bottom of your question add the code of your route. – smartrahat Dec 23 '15 at 19:42
  • @smartrahat oh, sorry, I have corrected my mistake. –  Dec 23 '15 at 19:50

2 Answers2

8

The solution is change

RewriteRule ^(.*)/$ /$1 [L,R=301]

to

RewriteRule ^(.*)/$ $1 [L,R=301]

And in my case clear cache in my browser :).

3

This works for me; removing all trailing slashes from all routes while emphasizing that REQUEST_URI starts with a slash (at least in .htaccess files):

Replace:

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

With:

# Remove all trailing slashes    
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L]

This will rewrite mywebsite.com/laravel/test/ to mywebsite.com/laravel/test/ without redirecting you mywebsite.com/test

Just don't use %{REQUEST_URI} (.*)/$. Because in the root directory REQUEST_URI equals /, the leading slash, and it would be misinterpreted as a trailing slash.

SOURCE: https://stackoverflow.com/a/27264788/2732184

Community
  • 1
  • 1
bmatovu
  • 3,756
  • 1
  • 35
  • 37