How can I make all pages have "www" in front of them?

Member

by dorothea , in category: SEO , a month ago

How can I make all pages have "www" in front of them?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by priscilla.langworth , a month ago

@dorothea 

To ensure that all pages on your website have "www" in front of their URL, you can set up a redirect using either server-side configuration or using a code-based solution.


Here are two common ways to do this:

  1. Server-side configuration (e.g. Apache or Nginx):
  • Apache: Add the following code to your .htaccess file in the root of your website:RewriteEngine On RewriteCond %{HTTP_HOST} !^www. [NC] RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
  • Nginx: Add the following code to your server block configuration file:server { listen 80; server_name example.com; return 301 $scheme://www.$server_name$request_uri; } server { listen 80; server_name www.example.com; ... # your normal server block configuration }
  1. Code-based solution (e.g. PHP or JavaScript):
  • PHP: You can add the following code to the top of each of your PHP files:<?php if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') { header('Location: http://www.' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); exit; } ?>
  • JavaScript: You can add the following code to your HTML file(s), typically in the head section:<script> if (window.location.hostname !== 'www.example.com') { window.location.href = 'http://www.example.com' + window.location.pathname + window.location.search; } </script>


Note: You will need to replace "example.com" with your own domain name in the code examples above. Additionally, if your website is using HTTPS, you should use "https://" instead of "http://" in the redirects.