Search code examples
apache.htaccesshttp-redirecthttp-status-code-301

.htaccess and how to set RewriteEngine correctly


I own these 4 domains:

-example.it
-www.example.it
-example.com
-www.example.com

I want them all to 301 redirect to www.example.com. I'm currently running Apache2 on Ubuntu.

What is the correct syntax for my .htaccess file?

Thank you :)


Solution

  • You can use the following RewriteRule in your htaccess file :

    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteCond %{HTTP_HOST} ^(www\.)?(example\.com|example\.it)$
    RewriteRule ^ http://www.example.com%{REQUEST_URI} [NE,L,R=301]
    

    Short explaination :

    The first RewriteCond excludes the destination domain www.example.com We have excluded it to avoid the Redirect loop error. The second condition matches either www.example.it , example.com or example.it and then the rule redirects the request to www.example.com .