Marcello Impastato Marcello Impastato - 1 year ago 95
Apache Configuration Question

http redirect with htaccess updating url only

working with .htaccess i solved about the url conversion from (for example):

(a) http://www.mydomain.ext/dir/myfile.php


(b) http://www.mydomain.ext/dir/myfile

(deleting the .php) to end. But if user from web typing as in (a) them display the url so as typed.
How i can solve becouse typing as in (a) webserver display too as in (b) ?
I thinked about a redirect from (a) to (b) but not think that it is the best solution, what suggest for solve it?
Thanks very much for help.

Try to explain better the question with a concrete example. Starting from .htaccess i have:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php

and i solved it using PHP so:

$default_url = "http://".$_SERVER["HTTP_HOST"].$_SERVER

["REQUEST_URI"]; // display something as: http://www.mysite.ext/dir/filename.php
$canonical_url = str_replace(".php", "", "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]); // display something as: http://www.mysite.ext/dir/filename
if ( $default_url != $canonical_url ) {
header( 'Location: ' . $canonical_url, true, 301 );

I ask as update the .htaccess code for integrate about feature descripted in PHP script. I have looked much example but not solve it.
Thanks very much.

Answer Source

To convert my comments into an answer, have these rules in your root .htaccess:

RewriteEngine on

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

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download