开发者

Redirect Non-WWW to WWW URLs

When people access my domain it is redirected to http://www.mydomain.com/en/index.php using php code.I added the fo开发者_StackOverflow中文版llowing code in .htaccess

RewriteEngine on
Options +FollowSymlinks

RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RedirectPermanent /pages/abc-123.html http://www.mydomain.com/en/page-a1/abc.php

to redirect people from non www to www,

Still users can access by typing both http://mydomain.com/en/page-a1/abc.php and http://www.mydomain.com/en/page-a1/abc.php URLs

Does anyone know the method to completely redirect to http://www.mydomain.com/en/page-a1/abc.php even if user typed http://www.mydomain.com/en/page-a1/abc.php, and prohibit accessing URLs without www.


$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


<?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


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']);


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]


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


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜