• February
  • 2nd
  • 2009

Rewrite www to no-www

Posted by MaEl in: Bits-and-Bytes Comments (0)


Redirection via webserver

Most of popular webserver support redirection. The flow of redirection using this method is

Browser -> Web Server

Below is configuration for popular web server

Apache

Redirection in Apache requires the mod_rewrite module.
Put this in .htaccess file
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,L]

Alternative,
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www. [NC]
RewriteRule ^(.*)$ %{HTTP_HOST}/$1 [C]
RewriteRule ^www.(.*)$ http://$1 [L,R=301]

Nginx

Nginx doesn’t support .htaccess file.
Redirection can easily be configured in the configuration file. But you need the access to nginx configuration file. Don’t forget to reload nginx after finished.
server {
server_name www.domain.tld;
rewrite ^/(.*) http://domain.tld/$1 permanent;
}

permanent means 301 redirect. without the permanent keyword, nginx send a 302 redirect.

Lighthttpd

Like nginx, lighthttpd also doesn’t support .htaccess file.
Rewrite requires mod_redirect module. Put this in configuration file, then reload.
$HTTP["host"] =~ "^www\.(.*)$" {
url.redirect = ( "^/(.*)" => "http://%1/$1" )
}

Redirection via script(dynamic)

This method requires a dynamic scripting language on the server side. Using this method, the flow is a bit longer.

Browser -> Web Server -> Dynamic Script

PHP

Put this code on top of your php script.
<?php
if (strpos($_SERVER['HTTP_HOST'], 'www.') === 0) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://'.substr($_SERVER['HTTP_HOST'],4).$_SERVER['REQUEST_URI']);
exit();
}
?>

Alternative,
<?php
if (!preg_match("/^www./i",$_SERVER['HTTP_HOST'])){
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://'.substr($_SERVER['HTTP_HOST'],4).$_SERVER['REQUEST_URI']);
exit();
}
?>

ASP

« google bug? False “This site may harm your computer” | decryt ssl key »


Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>