Číst česky →

How to redirect a URL via .htaccess (setting 301 redirects)

1 min read Hukot net WebHosting Apache

301 Redirect, also known as permanent redirection, informs search engines that a specific address has been permanently moved to another location. It is commonly used to handle duplicate content, website relocation, or redirecting non-existent pages to new ones.

In Apache2, we use the Redirect and RedirectMatch directives from the mod_alias module, and the mod_rewrite module for more complex rules. The configuration is done in the .htaccess file.

For RewriteCond and RewriteRule rules, enable the mod_rewrite module in the .htaccess file with the following line:

RewriteEngine On

After that, we can perform redirects using the following methods:

# Redirects URLs whose path starts with /old-url (including subpages)

Redirect 301 /old-url /new-url

# Redirects URLs whose path starts with /old-url/

RedirectMatch 301 ^/old-url/(.*)$ /new-url/$1

# Redirects to the result if the condition is met

RewriteCond <test string> <condition>

RewriteRule <pattern> <target> [flags]

Examples

# Individual pages

Redirect 301 /old-url.html http://mydomain.com/new-url
# Individual folders

RedirectMatch 301 ^/old-folder/(.*)$ http://www.mydomain.com/new-folder/$1
# From www.mydomain.com to mydomain2.com

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.mydomain\.com [NC] 

RewriteRule ^(.*)$ http://mydomain2.com/$1 [L,R=301]

You can find instructions on how to set up HTTP to HTTPS redirection in the guide How to Redirect HTTP to HTTPS.