0

How can I delete the .php extension from URL with mod_rewrite?

For example:

test.com/index.php -> test.com/index/
test.com/contact.php -> test.com/contact/

2 Answers 2

1
RewriteEngine on
RewriteRule ^([^/]+)/?$ $1.php

If the user typed in http://example.com/index/ they would get the actual page of http://example.com/index.php

Basically this rule says "match everything from the base url up to a slash, or the end if no slash, but not including the slash. Then give the user that matched part with .php appended to the end."

This is only going to work for the first level of directory; ie. this will not match on example.com/index/some/other/stuff - no redirect there.

Sign up to request clarification or add additional context in comments.

3 Comments

i want to first level only. but your code get error "500 Internal Server Error".
index.php is also matched by ^([^/]+)/?$.
A little tweak: RewriteRule ^([^\/\.]+)/?$ $1.php [L,NS]. It should work now ;)
0

If you really want to redirect requests to /index.php to /index/, try this rule:

RewriteCond %{THE_REQUEST} ^[A-Z]+\ (/[^?\ ]+)\.php[?\ ]
RewriteRule .+\.php$ %1/ [L,R=301]

And for the other direction:

RewriteRule (.+)/$ $1.php [L]

You can also use both rules at the same time to get this behavior:

  • requests of /index.php are getting redirected externally to /index/
  • requests of /index/ are getting rewritten internally to /index.php

2 Comments

tanks gumbo. i want show index.php but in url show index/. ok?
@chalist: So you requested /index.php or /index/ and it didn’t work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.