Reputation: 981
My htaccess is located in localhost/me/.htaccess
, and I want to append anything after the last / with .php
e.g. localhost/me/test/index
rewrites to localhost/me/test/index.php
So far RewriteRule ^([A-Za-z]+)$ $1.php [NC,L]
works for localhost/me/index
, but I can't get it working for the first example up there. Why doesn't ^/([A-Za-z]+)$ /$1.php [NC,L]
work, and how do I change it to work?
Upvotes: 1
Views: 173
Reputation: 165168
Use this rule:
# add .php file extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [L,QSA]
It will check if such .php exist before rewriting
The main problem you had is your pattern: ^([A-Za-z]+)$
it will match index
but not test/index
as it only allows a-z
characters. You would need to add /
into a pattern: ^([a-z/]+)$
.
because you have [NC]
flag (no case matching), there is no need to have both A-Z
and a-z
I'm using more global/general pattern (.+)
-- it will match any characters and because it comes with "check if file exist" conditions, there is no need to worry about limited set of characters.
Upvotes: 2
Reputation: 270627
It doesn't work because you're matching only on alpha letters and you don't have a /
in the character class, but your URI is me/test/index
. Try this:
RewriteEngine On
RewriteRule ^([A-Za-z/]+)$ $1.php [NC,L,QSA]
Also, since you're using [NC]
, you really only need a-z
rather than A-Za-z
but it doesn't hurt anything.
Upvotes: 1