netizen0911
netizen0911

Reputation: 461

PHP/.htaccess - Redirect visitor when accessing page with .php extension

I want my visitors to get redirected when they access pages with .php extension name. To make it a bit clearer:

I currently have .htaccess set to remove .php extension from URL in which when visitor types in www.mysite.com/about/ it loads the www.mysite.com/about.php content. I basically want the same thing happen in reverse like:

When visitor enters www.mysite.com/about.php into the address bar, I want to load the same content, but redirect/change the URL to www.mysite.com/about/ and appear in the address bar.

Thanks in advanced! Paul G.

Upvotes: 0

Views: 312

Answers (2)

anubhava
anubhava

Reputation: 784908

You can use this code:

# To externally redirect /index.php to /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\sindex(\.php)?[\s?] [NC]
RewriteRule ^ / [R=301,L]

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php[\s?] [NC]
RewriteRule ^ %1 [R=301,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [L]

Upvotes: 1

Gevork Palyan
Gevork Palyan

Reputation: 46

Hi this seemed to work for me:

RewriteEngine on
RewriteRule ^(.*)\.php$ $1 [R]

Essentially this throws away the .php from your url and keeps everything else.

Upvotes: 0

Related Questions