Infinity
Infinity

Reputation: 898

Mod_rewrite to remove PHP extension and redirect

I've read and tested many solutions, but couldn't get working correctly.

WHAT I NEED?

If user type in address bar .../etc.php It should be redirected to .../etc/, also .../etc/ should be able to access directly, some examples:

www.mysite.com/index.php - > www.mysite.com/

www.mysite.com/register.php - > www.mysite.com/register/

www.mysite.com/profile.php?id=123 - > www.mysite.com/profile/123/

Also if lang parameter is set to en (only en, otherwise not show lang value at address bar) It should add /en/ after root, something like:

www.mysite.com/register.php?lang=en - > www.mysite.com/en/register/

www.mysite.com/index.php?lang=en - > www.mysite.com/en/


WHAT I'VE TRIED

Options -MultiViews

RewriteEngine on
RewriteBase /

# url is ONLY '/en' or '/de' -> redirect to /en/ or /lt/ (adding slash)
RewriteRule ^(en|lt)$  $1/ [R=301,L]

# now all urls have en/ lt/ -> parse them
RewriteRule ^(en|lt)/(.*)$  $2?lang=$1&%{query_STRING} [L]
# no "R=301" here --------------------------------------^

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

But the code above let user access both www.mysite.com/register.php and www.mysite.com/register/, whereas It should redirect (change url) from www.mysite.com/register.php to www.mysite.com/register/

Upvotes: 1

Views: 263

Answers (1)

anubhava
anubhava

Reputation: 784898

I suggest this redirect rule that removed .php extension and index.php from URLs:

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} /+(.*?/)?(?:index)?(.*?)\.php[/\s?] [NC]
RewriteRule ^ %1%2/ [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Upvotes: 1

Related Questions