Search code examples
.htaccesshttp-redirectmod-rewrite

htaccess non-www to www rule doesn't work


For a customer of mine I tried different versions of the .htaccess rule to forward/redirect all the "non-www" URL to the corresponding www one.

My current .htaccess is the following:


# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# Redirection from non-www to www ---> latest rule used
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]


AddHandler application/x-httpd-php81 .php .php5 .php4 .php3

So...

I tried 3 different rules without any result (apart from having a 301 for the homepage ONLY). My hosting is SG. Any ideas/help?

I tried different rules, like the one published above and:

#test 1 (same as above)

RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

#test 2

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]

#test 3

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Nothing to do, none of these rules help me to redirect all the non-www URLs to the www ones.


Solution

  • You've put the rule in the wrong place. This "redirect" rule needs to go at the top of the .htaccess file, before the WordPress code block (rewrite to the WP front-controller), ie. before the # BEGIN WordPress comment marker.

    Otherwise, any of your "tests" would work, although you are erroneously redirecting to http (not https) in "test2". You do not need to repeat the RewriteEngine On directive here (that already occurs later in the .htaccess file - in the WordPress code block).

    Test first with 302 (temporary) redirects to avoid potential caching issues.

    By placing the rule at the end of the file (ie. after the WordPress front-controller pattern) then it's only going to be processed for the "homepage" and static assets - internal WordPress pages will not be redirected. (The "homepage", ie. the root directory, and static assets are not processed by the WordPress code block, so processing drops through to the rule at the end.)