AnchovyLegend
AnchovyLegend

Reputation: 12538

php 301 redirect to all t

According to: Daily Blog Tips

The code below does two things:

1) It will add (or remove) the www. prefixes to all the pages inside your domain.

2) The code below redirects the visitors of the http://domain.com version to http://www.domain.com.

My question: Is inserting the code below in the index.php page sufficient to create a 301 redirect that will work on all pages of the website I am working on?

<?php
if (substr($_SERVER['HTTP_HOST'],0,3) != 'www') {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://www.'.$_SERVER['HTTP_HOST']
.$_SERVER['REQUEST_URI']);
}
?>

Upvotes: 0

Views: 477

Answers (1)

Anthony Hatzopoulos
Anthony Hatzopoulos

Reputation: 10547

My question: Is inserting the code below in the index.php page sufficient to create a 301 redirect that will work on all pages of the website I am working on?

No. That will only work for http://www.example.com/index.php and not for http://www.example.com/whatever/whatever/file.php. You're better off using Apache mod_rewrite to accomplish this task. You could stick this in your document root /.htaccess file.

# Rewrite "example.com -> www.example.com".
<IfModule mod_rewrite.c>
  Options +FollowSymlinks
  RewriteEngine On
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
  RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

Code was taken from HTML5 Boilerplate's .htaccess

Upvotes: 3

Related Questions