How to configure redirection using .htaccess file. Htaccess is file which is used to make changes to your web server configuration without editing the server configuration file. This .htaccess file will be placed in your website root directory.
In this guide you are going to learn to how to configure some list of redirections which is mostly needed for your SEO and ranking in search engines.
These are the list of redirections you are going to learn here.
- Redirect HTTP to HTTPS with www.
- Redirect HTTP to HTTPS without www.
- Redirect one page to another page.
- Redirect old domain to new domain.
- Redirect old domain to new domain while preserving the path.
- Redirect files location to new domain with same path.
- Redirect except certain path.
- Redirect subdomain to subfolder.
Note: The below redirections use 301 permanent redirection, so you if need to can try the rules by using 302 temporary redirection instead and test them.
1. Redirect HTTP to HTTPS with www
RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]
2. Redirect HTTP to HTTPS without www
RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
3. Redirect one page to another page
Syntax is
Redirect type(302/301) old_location new_location
Redirect 301 /old_page https://www.domain.com/new_page Redirect 301 /old_page https://www.domain.com/folder/
4. Redirect old domain to new domain
RewriteEngine on RewriteCond %{HTTP_HOST} ^domain\.com$ [OR] RewriteCond %{HTTP_HOST} ^www\.domain\.com$ RewriteRule ^(.*)$ "https\:\/\/new-domain\.com\/" [R=301,L]
5. Redirect old domain to new domain while preserving the path
RewriteEngine on RewriteCond %{HTTP_HOST} ^olddomain\.com$ [OR] RewriteCond %{HTTP_HOST} ^www\.olddomain\.com$ RewriteRule ^(.*)$ "https\:\/\/newdomain\.com\/$1" [R=301,L]
6. Redirect files location to new domain with same path
RewriteRule ^.*\.(pdf|doc)$ https://newdomain.com%{REQUEST_URI} [R=301,L]
7. Redirect except certain path
For example if you wish to redirect all your website frontend to a new domain except your WordPress wp-admin pages, then you need to use the following rules before the redirection rules.
RewriteCond %{REQUEST_URI} !^(.*)?wp-login\.php(.*)$ RewriteCond %{REQUEST_URI} !^(.*)?wp-admin$ RewriteCond %{REQUEST_URI} !^/(wp-includes/.*|wp-admin/.*|wp-content/.*)$
8. Redirect subdomain to subfolder
This mainly used for redirecting a subdomain based site to a subfolder based site.
Options +FollowSymLinks RewriteEngine On RewriteCond %{REQUEST_URI}/ subfolder RewriteRule ^(.*) https://domain.com/%{REQUEST_URI} [R=301,NC] RewriteRule ^(.*) https://domain.com/blog/%{REQUEST_URI} [R=301,NC]