ForceMagic
ForceMagic

Reputation: 506

How to remove extension from url WITHOUT trailing slash using .htaccess?

I have a .htaccess file:

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

And I have a file called random.php.

All I want to do is just call something.com/random, but Apache adds a trailing slash (using 301 Redirect) to the end of the URL, therefore giving an error stating that something.com/random/.php cannot be found.

EDIT 1: When I use

RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [NC,L]

then my external files (.js, .css, etc.) can't load and the server responds with a 500 Internal Server Error response. Apache says that there were too many redirects.

Upvotes: 2

Views: 638

Answers (2)

Garytje
Garytje

Reputation: 874

You almost had it right, you just needed to exclude the slash as well:

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.\/]+)$ $1.php [NC,L]    

Upvotes: 1

anubhava
anubhava

Reputation: 785186

Try this rule with optional trailing slash:

RewriteEngine On

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

Upvotes: 2

Related Questions