Progmar Marcin Załęczny

Language:

Redirecting service from www to none-www and vice versa

In order to redirect a service from www to none-www (ex. http://www.service.pl => http://service.pl) you have to add two highlighted lines below in your htaccess file:


RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^www.service.pl
RewriteRule ^(.*)$ http://service.pl/$1 [R=301,L]

RewriteCond %{REQUEST_URI} (/|\.htm|\.php.*|\.html|\.xml|\.txt|/[^.]*)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php

The same effect you can achieve in php code (at the very top of your code):


if (strpos($_SERVER['SERVER_NAME'], 'www.') === 0) {
    $server = substr($_SERVER['SERVER_NAME'], 4);
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: http://' . $server . $_SERVER['REQUEST_URI']);
    exit();
}

The redirection in reversed order (np. http://service.pl => http://www.service.pl) you can make by adding following two highlighted lines to your htaccess file:


RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^service.pl
RewriteRule ^(.*)$ http://www.service.pl/$1 [R=301,L]

RewriteCond %{REQUEST_URI} (/|\.htm|\.php.*|\.html|\.xml|\.txt|/[^.]*)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php

Or in php code (at the very top of your code):


if (strpos($_SERVER['SERVER_NAME'], 'www.') !== 0) {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: http://www.' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
    exit();
}