Using .htaccess for Redirects Print

  • 0

Using .htaccess for Redirects

The .htaccess file is a powerful tool for managing redirects on your website. Below are the common types of redirects and how to implement them using the .htaccess file.

1. 301 Redirect (Permanent Redirect)

A 301 redirect indicates that a page has permanently moved to a new location. This is useful for SEO, as it passes link equity to the new URL.

Example: Redirect a Single Page

To redirect old-page.html to new-page.html, add the following line to your .htaccess file:

Redirect 301 /old-page.html /new-page.html

Example: Redirect a Domain

To redirect all traffic from one domain to another (e.g., from example.com to newexample.com), use:

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

2. 302 Redirect (Temporary Redirect)

A 302 redirect indicates that a page has temporarily moved. This is not cached by browsers, making it suitable for short-term changes.

Example: Redirect a Single Page

To temporarily redirect old-page.html to new-page.html, use:

Redirect 302 /old-page.html /new-page.html

3. Redirecting www to non-www (or vice versa)

To redirect all www requests to non-www:

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

To redirect non-www requests to www:

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

4. Redirecting Multiple URLs

If you have multiple pages to redirect, you can add multiple Redirect lines:

Redirect 301 /old-page1.html /new-page1.html Redirect 301 /old-page2.html /new-page2.html

5. Redirecting a Directory

To redirect an entire directory, you can do the following:

Redirect 301 /old-directory/ /new-directory/

Conclusion

Using the .htaccess file for redirects is a powerful way to manage traffic and improve SEO. Always remember to back up your .htaccess file before making changes, and test your redirects to ensure they work as intended. If you encounter issues, check for typos or syntax errors, as these can cause server errors.


Was this answer helpful?

« Back