pixie123
pixie123

Reputation: 979

.htaccess remove PHP extension conflicts with redirect trailing slash

I have three pieces of code.

Here's the first one:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

The second one:

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R,NE]

The third one:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-_]+)/$ profile/index.php?username=$1 [QSA,L]
  1. The first removes the .php extension from the URL bar
  2. The third shows the contents of a directory. For example, example.com/billgates/ shows the page content of: example.com/profile/index.php?username=billgates
  3. The second adds a trailing slash and redirects the non-trailing slash of the #2. For example, example.com/billgates redirects to example.com/billgates/.

All codes work but just not very nicely together. Here is the problem:

If I go to example.com/login it removes the .php extension and it works. BUT the problem is, if I manually add a trailing slash at the end of /login/, it redirects to: example.com/login/.php/ but it should redirect me to /login because it is not a directory and just a page. But if /login/ was a directory, then it shouldn't redirect.


Full .htaccess:

RewriteEngine On

ErrorDocument 404 /404.php

...the three pieces of codes above

Upvotes: 1

Views: 164

Answers (1)

anubhava
anubhava

Reputation: 786349

Have it this way and test after clearing browser cache:

ErrorDocument 404 /404.php

RewriteEngine On

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule /$ - [L,R=404]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)$ $1.php [L]


RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/$ profile/index.php?username=$1 [QSA,L]

Upvotes: 1

Related Questions