14

Possible Duplicate:
Remove .php extension with .htaccess

I want to make all my website URLs, myurl/webpageexamples.php, to be renamed to its non-extension version myurl/webpageexamples, if possible in .htaccess and at the same time redirect all traffic from myurl/webpageexamples.php to the new myurl/webpageexamples.

I have found several to redirect from PHP to non-PHP like:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.html$ /$1 [L,R=301]

What I have:

myurl/webpageexamples.php

What I want:

myurl/webpageexamples

I would like to have the SEO score transferred to new myurl/webpageexamples.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gorrion
  • 163
  • 1
  • 1
  • 6

1 Answers1

34

You want to make sure you are redirecting if the actual request is for a php page, and internally rewriting when the URI is missing the php:

RewriteEngine On

# browser requests PHP
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]

# check to see if the request is for a PHP file:
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*)$ /$1.php [L]
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • 1
    I think thats it. You are the master. Does it make any difference to have the check after the request? – Gorrion Nov 05 '12 at 22:23
  • Or would it be better to have the check first and then the browser requests? I guess as it is a 301 yhis will transfer all SEO from mypage.php to the new mypage, right? Thanks again – Gorrion Nov 05 '12 at 22:30
  • It doesn't matter what order, they're mutually exclusive. – Jon Lin Nov 05 '12 at 22:57
  • If I wanted (as I will be in a few days) also redirect all trafic from http to https what would I be adding to the code? Thank you. – Gorrion Nov 05 '12 at 23:08
  • How is it possible that works for some pages and not for another? Works on http://www.eldietista.es/buscar but it doesnt on http://www.eldietista.es/colectividades...????? Thanks for the help – Gorrion Jan 27 '13 at 18:11
  • Why did you use `[A-Z]{3,9}\ /([^\ ]+)` instead of `(.*)`? – Adam Feb 25 '18 at 12:15
  • The `%{THE_REQUEST}` variable includes the entire request, including the HTTP method. Example: `GET /blah.php HTTP/1.1`. We only want to match the "blah" part – Jon Lin Feb 25 '18 at 17:37
  • 2
    Warning: This looks like the most concise response to this question on SO, but all of the similar answers that I've seen don't account for `.php` in the query string (`GET /blah?tricked=you.php HTTP/1.1`). I believe changing `/([^\ ]+)\.php` to `/([^?\ ]+)\.php` would fix it. – stevo Sep 14 '19 at 07:14