Configure a redirect 301 in .htaccess is very easy. This redirection is used when we need to change urls of our websites and not lose the positioning of these urls when redirecting them.
This redirect warns search engines that the content has been permanently redirected to another url. Then the search engines reindex the new urls and we do not lose the positioning that we had gained before.
It is important that when I talk about url I mean that redirections can be applied to both server files and pages.
I will do the practical cases in .htaccess.
Among the examples we will see practical cases such as the redirection of a URL, domain redirection and directory redirection. The functions used will be:
‘redirect 301‘ is used to redirect a single url for each line of code in the .htaccess
While ‘redirectmatch 301‘ is used when we want to establish redirection rules using regular expressions (patterns), and thus all urls that meet those rules will be redirected to the new ones.
In this example code we want to redirect a url to another url.
RewriteEngine On RewriteBase / Redirect 301 /url.html https://www.yourdomain.com/newurl.html
The use of regular expressions in .htaccess is widely used due to the code saving it implies:
RewriteEngine On RewriteBase / #redirect all the content of a web to another domain respecting the structure of urls, let's see 2 ways to do it RedirectMatch 301 /(.*) https://www.yourdomain.com/$1 RedirectMatch permanent /(.*) http://wwws.yourdomain.com/$1 #redirect all the content of a web to the home page of another domain, I give you 2 examples RedirectMatch 301 ^(.*)$ https://www.yourdomain.com RedirectMatch permanent ^(.*)$ https://www.yourdomain.com #redirect the content of a directory to a new one respecting the url structure from the redirected directory, also applies if the new address is in another domain RedirectMatch 301 /current-directory/(.*) https://www.yourdomain.com/new-directory/$1 RedirectMatch permanent /current-directory/(.*) https://www.yourdomain.com/new-directory/$1
RewriteRule does the same function as RedirectMatch only with different declaration, I give you an example:
RewriteEngine On RewriteBase / RewriteRule /current-directory/(.*) https://www.yourdomain.com/new-directory/$1 [R=301,L]
With these 3 ways of doing redirect 301 we cover most of the needs that we will usually have.