Drahcir
Drahcir

Reputation: 981

mod_rewrite last match

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

Answers (2)

LazyOne
LazyOne

Reputation: 165168

Use this rule:

# add .php file extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [L,QSA]
  1. It will check if such .php exist before rewriting

  2. 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/]+)$.

  3. because you have [NC] flag (no case matching), there is no need to have both A-Z and a-z

  4. 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

Michael Berkowski
Michael Berkowski

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

Related Questions