How to do a 301 Redirect in an .htaccess file

The server response code (i.e. 301 v.s 302) can have a significant impact to the crawlers and bots that crawl your site. I wrote about that in some detail in an article titled, “What is the difference between 301 and 302 redirects in SEO?

But the purpose of this article to simple outline how to add a 301 redirect to your .htaccess file, not explain server response codes.

Here is the 301 redirect code of the .htaccess file:

Redirect 301 /oldpage https://www.domain.com/NewPageURL

You would replace “oldpage” with the relative path to the page that you are wanted to direct traffic from and then replace “https://www.domain.com/NewPageURL” with the absolute path of the URL that you are wanting to send that traffic to.

.htaccess Redirect Tips

  1. The spacing is important
  2. The “/” before the relative path is important
  3. 1 redirect command per line

Redirect www to non-www with .htaccess file

It occurred to me that just maybe you don’t want to display your site with the www subdomain prefix. In that case you could deploy the following code in your .htaccess file to redirect www to non-www. By doing so, users will access your site at http://domain.com not http://www.domain.com.

.htaccess

If your website is hosted on an apache server, a redirect from www to non-www is a simple implementation. Add the following to your .htaccess file.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^domain\.com
RewriteRule (.*) http://domain.com/$1 [R=301,L]

Add the above code to you .htaccess file and replace domain.com with your domain name.

This post is a follow-up to a similar adrticle on how to redirect non-www to www with .htaccess.

Use .htaccess to redirect non www to www

htaccess redirectIt’s is considered good practice, for both SEO and users, to have your website resolve to one URL. Technically speaking www.domain.com is a subdomain of domain.com. Users often type www. prior to the domain in the address bar. So to keep that formality consistent with your users you can redirect the traffic on domain.com to www.domain.com.

.htaccess

If your website is hosted on an apache server, this redirect from non www to www is a simple implementation. Add this to your .htaccess file.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteRule (.*) http://www.domain.com/$1 [L,R=301]

Add the above code to you .htaccess file and replace domain.com with your domain name.

I have another post on how to redirect www to non-www with .htaccess.