How to Use .htaccess for Redirects and Friendly URLs Print

  • 0

The .htaccess file in your public_html folder lets you control redirects and URL rewriting yourself. It's useful when cPanel's Redirects tool isn't flexible enough, or when you want short, clean URLs. Below are ready-to-use examples. Replace example.co.uk and the page names with your own.

Before you edit

  • Download a copy of the file or duplicate it in File Manager first. See how to edit the .htaccess file.
  • If your site uses WordPress, put your rules above the # BEGIN WordPress block. WordPress rewrites everything between # BEGIN WordPress and # END WordPress, so anything you add there will be lost.
  • A 500 Internal Server Error straight after saving means there's a syntax error. Restore your backup copy, or remove the lines you just added.

Redirect one page to another

Redirect 301 /old-page.html https://example.co.uk/new-page/

Redirect a whole domain to a new one

This keeps the rest of the path, so /about goes to /about on the new domain:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?old-example\.co\.uk$ [NC]
RewriteRule ^(.*)$ https://example.co.uk/$1 [R=301,L]

Force HTTPS

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

cPanel can also do this without editing any files. See how to force HTTPS.

Redirect www to non-www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.co\.uk$ [NC]
RewriteRule ^(.*)$ https://example.co.uk/$1 [R=301,L]

Redirect non-www to www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.co\.uk$ [NC]
RewriteRule ^(.*)$ https://www.example.co.uk/$1 [R=301,L]

Pick one of these two, never both.

Friendly URLs

A rewrite shows a short address while serving a file from somewhere else. The visitor's address bar doesn't change. This example serves /files/folder/sitemap.html when someone visits example.co.uk/sitemap:

RewriteEngine On
RewriteRule ^sitemap/?$ /files/folder/sitemap.html [L]

Good to know

  • RewriteEngine On only needs to appear once in the file, before your first rule.
  • Test redirects in a private window. Browsers remember 301 redirects, so a mistake can stick in your normal browser even after you fix it.
  • For simple redirects you can use cPanel instead. See how to redirect a domain or page in cPanel.

Was this answer helpful?

« Back