I recently managed to direct all URLs from non-www to www as I had an SEO error regarding duplicate websites.
Once I have applied www rules then all my URLs start showing index.php?page=
which doesn't look pretty.
Here are my current .htaccess
rules:
RewriteEngine On
RewriteBase /
RewriteRule ^([-a-zA-Z0-9]+)$ index.php?page=$1
RewriteCond %{HTTP_HOST} !^www.example.com$
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
RewriteEngine On
RewriteBase /
# Removes index.php?page=$1
RewriteCond %{THE_REQUEST} ^.*/index.php?page=$1
RewriteRule ^(.*)index.php?page=$1$ https://www.example.com/$1 [R=301,L]
RewriteRule ^(.*)index$ https://www.example.com/$1 [R=301,L]
I have tried the code above and it didn't work. Is there anything I am missing?
Your rules are in the wrong order. Your external non-www to www redirect needs to be before the internal rewrite, immediately after the first
RewriteBase
directive.As a general rule, "redirects" should always go before "rewrites".
UPDATE: You will need to make sure you've cleared your browser cache (and any intermediary caches) since the erroneous 301 (permanent) redirect will have certainly been cached by the browser.
In summary, your rules should look like this:
Any literal dots in the regex need to be backslash escaped. And you should include the
L
flag on the rewrite should you add additional rules later.(NB: I assume you are linking to URLs of the form
/this-is-my-page
and not/index.php?page=this-is-my-page
- otherwise you need to change your internal links.)