aleixrav
aleixrav

Reputation: 214

.htaccess avoid accessing files with .php after rewrite

I applied a rewrite rule to show my php files without the .php at the end of the file. This is what I have:

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

But the problem I have is that I can access that file with two ways. With or without the .php. For example: mywebsite.com/file.php and mywebsite.com/file both work but I just want the second one to work so I need to add something to my .htaccess file to redirect mywebsite.com/file.php to mywebsite.com/file or show a 404 error. But I think the first option is better.

Is it possible to combine my .htaccess code with what I want? And if so, what is needed to be added?

Upvotes: 1

Views: 56

Answers (1)

Amit Verma
Amit Verma

Reputation: 41219

You can use this rule to remove .php extension

RewriteEngine on
#1)externally redirect from "/file.php" to "/file"
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [L,R]
#2)internally map "/file" to "/file.php"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Upvotes: 1

Related Questions