How To Redirect http to https & non www to www

jriddick

Stealth Assassin
Mar 8, 2010
228
4
0
I have an SSL site.

I want to set up a redirect that will automatically send the visitor to "https://www.mysite.com".

So whether they type in "mysite.com" or "http://mysite.com" or http://www.mysite.com" or https://mysite.com"...

I want all of those to redirect to one, clean "https://www.mysite.com"

Any suggestions?
 


Add this to your .htaccess file (assuming you're running Apache)
Code:
RewriteEngine On

#non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

#force ssl
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
 
Add this to your .htaccess file (assuming you're running Apache)
Code:
RewriteEngine On

#non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

#force ssl
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

this. edit htaccess in your root directory
 
can also use php if you don't use htaccess

if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == ""){
$redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
header("Location: $redirect");
}
 
You should write rewrite rules to do it. I think you can modify htaccess file on your apache server to achive your goal
 
can also use php if you don't use htaccess

if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == ""){
$redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
header("Location: $redirect");
}

Except that it would need to be placed in every file, assuming of course a global header isn't being used, but still easier to just use .htaccess.