Sun

URL rewriting rules

  1. Home
  2. Knowledge Base
  3. Hosting
  4. CPanel
  5. Web Hosting
  6. URL rewriting rules

In all servers, mod_rewrite module is installed, which, provides a lot of possibilities for URL rewriting. You will need to use the .htaccess file that is located in the public_html directory on the site or in the directory you want to rewrite. If this file does not exist, you can simply create it.

The rule starts working when it is written to the .htaccess file. Here are some of the most popular examples:

Forwarding from http://my-site.com to http://www. my-site.com

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

Redirect from the old site to new

RewriteEngine On
RewriteRule ^(.*)$ http://www.new-site.com/$1 [R=301,L]

Moving visitors to the main subdomain

E.g. if your website is accessible via the link http://my-site.com/subdomain and link need be http://subdomain.my-site.com

RewriteEngine on
RewriteRule ^subdomain/(.*)$ http://subdomain.my-site.com/$1 [R=301,L]

If necessary, an exception can be made, eg. no change will be made to http://my-site.com/dont-change

RewriteEngine on
RewriteCond %{REQUEST_URI} !/dont-change
RewriteRule ^subdomain/(.*)$ http://subdomain.my-site.com/$1 [R=301,L]

Redirecting one part of a site

redirect 301 /work/file.html http://www.other-site.com/new/file.html

Redirecting all but one visitors

Useful when a website is still being created and anyone except the developer wants to display one version of the site.

To redirect visitors to the next page:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_HOST} !^127\.0\.0\.1
RewriteRule (.*) http://another-address.com/$1 [R=301,L]

To display a particular file:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_HOST} !^127\.0\.0\.1
RewriteRule \.html$ /other-page.html [R=302,L]

To direct visitors to another directory in the same domain (for example, “test”):

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_HOST} !^127\.0\.0\.1
RewriteRule ^((?!test/).*?)/?$ test/$1 [L,NC]

If you need to add multiple IP addresses, they are separated by “|”:

RewriteCond %{REMOTE_HOST} !^127\.0\.0\.1|^195\.36\.67\.134|^195\.157\.64\.5

Exception

Special rules can be created when redirection does not work. Ex. this rule would stop redirecting if the address to be opened is http://my-site.com/file.txt

RewriteCond %{REQUEST_URI} !/file.txt [NC]

Achieving a website from a subdirectory

If you want to access the site from level 1 below the directory (subdirectory) (i.e. public_html/test), insert the following code into the .htaccess file in the main directory (public_hml):

RewriteEngine on
RewriteBase /
RewriteRule ^((?!test/).*?)/?$ test/$1 [L,NC]

Was this article helpful?

Related Articles