Redirecting URLs not related to WWW-WWW

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

redirect users from non www to www ,

Users can access by typing http://mydomain.com/en/page-a1/abc.php and http://www.mydomain.com/en/page-a1/abc.php URL

Does anyone know that the method is completely redirected to http://www.mydomain.com/en/page-a1/abc.php , even if the user typed http://www.mydomain.com/en/page-a1/ abc.php and deny access to URLs without www.

+6
source share
6 answers
 $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

+11
source

I am not sure how to do this via .htaccess, but I do it with the PHP code in my config.php , which is loaded for each 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're right, I forgot about https

Edit

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

Add RewriteEngine On to RewriteCond to enable 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] 
+1
source
 <?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 right

+1
source
 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
source

I think you want to redirect the user instead of rewriting the URL, in this case use the Redirect or 'RedirectMatch` directive. http://httpd.apache.org/docs/2.3/rewrite/remapping.html#old-to-new-extern

0
source

Source: https://habr.com/ru/post/896113/


All Articles