When people access my domain it is redirected to http://www.mydomain.com/en/index.php using php code.I added the following code in .htaccess
RewriteEngine on
I think you want to redirect the user instead of rewriting the URL, in that case use Redirect
or 'RedirectMatch` directive. http://httpd.apache.org/docs/2.3/rewrite/remapping.html#old-to-new-extern
$protocol = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);
exit;
}
in php
Add RewriteEngine On
before RewriteCond
to enable your rewrite rules:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
And if you have https:
RewriteEngine On
RewriteRule .? - [E=PROTO:http]
RewriteCond %{HTTPS} =on
RewriteRule .? - [E=PROTO:https]
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ %{ENV:PROTO}://www.%{HTTP_HOST}/$1 [R=301,L]
<?php
$protocol = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;
}
?>
Working Properly
Redirect 301 /pages/abc-123.html http://www.mydomain.com/en/page-a1/abc.php
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on
# mydomain.com -> www.mydomain.com
RewriteCond %{HTTP_HOST} ^mydomain.com
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]
</IfModule>
I'm not sure how to do it through .htaccess, but I do it with PHP code myself within my config.php
which is loaded for every file.
if(substr($_SERVER['SERVER_NAME'],0,4) != "www." && $_SERVER['SERVER_NAME'] != 'localhost')
header('Location: http://www.'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
EDIT: @genesis, you are correct I forgot about https
Change
header('Location: http://www.'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
to
header('Location: '.
(@$_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://').
'www.'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);