PinoyStackOverflower
PinoyStackOverflower

Reputation: 5302

remove .php in URLs if users enters .php on the browser

I already successfully removed the .php file extension by configuring my .htaccess file, my problem here is that when a user types on .php on the URL, I wanted the user to be redirected incase they type in the .php on the URL. So for example, my original URL is

http://mysite.com/home

Sometimes, the user will type like this http://mysite.com/home.php, so in this case, I wanted to redirect them to a url without .php, so it should be http://mysite.com/home

Another example would be if a URL has a parameter, so for example:

http://mysite.com/home.php?id=1&uid=100

I want the user to be redirected to http://mysite.com/home?id=1&uid=100

Any ideas how to do this? Your help will be greatly appreciated and rewarded! Thanks :)

Upvotes: 1

Views: 665

Answers (3)

Jon Lin
Jon Lin

Reputation: 143906

You'll need to match against the actual request instead of the URI because your other rules are rewriting the URI. So something like this:

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

So if someone types: http://mysite.com/some/path/home.php, the browser will get redirected (thus changing the URL in the address bar) to http://mysite.com/some/path/home.

If you only want to do this for php files in your document root (e.g. /home.php and not /some/path/to/home.php) then tweak the regex:

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

Upvotes: 2

Oliver Tappin
Oliver Tappin

Reputation: 2541

Use .htaccess. Here's some code I currently use on my sites which replace /page.php to /page/:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]
RewriteRule ^(.*)\/$ $1.php [NC]

Put this in a file called .htaccess - No name, the 'extension' in this case, is the file itself. Save and upload to the server in your public_html folder. Or whatever your base/public directory is.

The last line in this code is the one that helps you, it replaces any file ending in .php file to a file with a / at the end, as explained above. Line 2 and 3 forward http://domain.com to http://www.domain.com. I don't know about you but I think it looks better like that.

Upvotes: 0

B-and-P
B-and-P

Reputation: 1713

Try something like this at the top of your file:

if (strpos($_SERVER['REQUEST_URI'],'.php')!==false){
$good_path = str_replace($_SERVER['REQUEST_URI'],'.php','');
header('Location: '.$good_path);
}

Better to use regex to check for extension, but this is a quick example only to get you started.

Upvotes: 0

Related Questions