AymDev
AymDev

Reputation: 7609

mod_rewrite redirects with absolute path in URL

I am trying to use Apache mod_rewrite. The first thing I did was to rewrite my url to an index.php file which was working fine. But I thought I should remove the trailing slash(es) too because I would prefer this to be handled by Apache instead of my PHP router.

Here's the whole content of my .htaccess file:

RewriteEngine on

# one of the attempts to remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.*)/+$
RewriteRule ^(.*)/+$ $1 [R=301,L]

# This is the rewriting to my index.php (working)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?/$1 [L]


The issue:
I read several questions about trailing slash removal but I could not find a working answer for me:
For every answer I tried, I was able to reach my PHP router index.php (located in Phunder\public\) without trailing slash:

// Requested URL                                | No redirection
http://localhost/projects/Phunder/public/home   | http://localhost/projects/Phunder/public/home

But when requesting the same page with a trailing slash I get redirected with the absolute path included:

// Requested URL                                | Wrong redirection
http://localhost/projects/Phunder/public/home/  | http://localhost/C:/xampp/htdocs/projects/Phunder/public/home


Other informations:

I'm a beginner with mod_rewrite I'm not always understanding what I try (sadly). Is there something I missed or misused ? What should I do to get the expected behaviour ?

Upvotes: 1

Views: 1322

Answers (1)

anubhava
anubhava

Reputation: 785631

Redirect rules need either absolute URL or a RewriteBase. You can extract full URI from %{REQUEST_URI} as well like this:

RewriteEngine on

# one of the attempts to remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(.+)/+$
RewriteRule ^ %1 [R=301,NE,L]

# This is the rewriting to my index.php (working)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

Upvotes: 1

Related Questions