Oswaldo C. Oswaldo C. - 9 days ago 5
PHP Question

How to remove .php and get var after slash on .htaccess

Good day. I need to remove .php at the end of a file and also get the last /var into a php $_GET var from .Htaccess.

I want this url rewrite:

http://example.com/file/123


into

http://example.com/file.php?id=123


But this must work if file is index.php like this:

http://example.com/123


into

http://example.com/index.php?id=123


Thanks for all your help :)

Answer

You can use these rules in site root .htaccess:

RewriteEngine On

# skip all files and directories from rewrite rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([\w-]+)/?$ index.php?id=$1 [L,QSA]

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([\w-]+)/([\w-]+)/?$ $1.php?id=$2 [L,QSA]