Searching...

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

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 mod_rewrite module to achieve this, and the configuration is done in the .htaccess file.

In the .htaccess file, we enable the mod_rewrite module with the following line:

RewriteEngine On

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

# Redirects all URLs containing 'old-url' in the name
Redirect 301 old-url new-url

# Redirects URLs containing '/old-url/' in the name
RedirectMatch 301 ^/old-url/(.*)$ /new-url/$1

# Redirects to the result if the condition is met
RewriteCond %condition% &
RewriteRule %result%

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
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.

Comments

To submit comment you have to be logged-in