How To Redirect and Rewrite URLs with .htaccess File

URL Redirect in a .htaccess file empowers you to divert visitors from a page to another page without keeping the old page. For instance, earlier you were using a URL example.com/oldpage.html as your list record and  later rename oldpage.html to example.com/newpage.html, you could set up a 301 redirect to send visitors to new URL.

.htaccess file gives super power to rewrite URLs in SEO friendly or human readable form. For example You have website URLs like. Read about importance of URL rewriting in SEO. It is an essential part of On page search engine optimisation.

url redirect htaccess

http://example.com/?p=1 You can rewrite these URLs in form like http://example.com/seo-tips

301 Redirect URLs with htaccess File

Make sure you have apache server you can find .htaccess file in the root folder where your website’s file hosted. Read more about URL Redirect in Apache

Redirect 301 /oldpage.html /newpage.html

Redirect your website from WWW to without www version – Example If you wish to run your website of http://example.com and when any user type http://www.example.com it will redirect to http://example.com. Use following code for htaccess

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]
Redirect your website from non WWW to www version – Example If you wish to run your website of http://www.example.com and when any user type http://example.com it will redirect to http://www.example.com. Use following code for htaccess

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

htaccess Redirect in WordPress Website – You can use any of the WordPress Redirect Plugins or You can redirect URLs with help of htaccess file.

Important Note – Make sure you put redirect code just below the line “RewriteEngine On”

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

So the code of redirecting /oldpage to /newpage will be

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
Redirect 301 /oldpage /newpage
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

You can also add multiple redirects in htaccess file as below

# BEGIN 301 Redirects
Redirect 301 /old-page /new-page
Redirect 301 /old-page-2 /new-page-2
Redirect 301 /old-page-3 /new-page-3
# END 301 Redirects

 

Leave a Reply

Your email address will not be published. Required fields are marked *