When I type http://mywebsite.com my server redirects successfully to http://www.mywebsite.com but when I type http://mywebsite.com/page.php it redirects to http://www.mywebsite.com not to http://www.mywebsite.com/page.php .
My server is Apache, I use these lines to redirect from non-www to www in my .htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} !^(.*).mywebsite.com$ [NC]
RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [R=301,L]
Thanks
4
Answers
I’d rather use this if you want to add a
www
at the start of your url if none exists :Try it like this:
Or to redirect ot HTTPS:
I would suggest the following:
I think your condition was being too strict. You were ending it (
$
) too soon.I do not recommend redirecting users to the in the .htaccess. You should do that in the config file for the virtual host if possible, using a temporary redirect, or permanent if appropriate, for visitors coming from a non http port (e.g. 80).
It might look something like this:
Then in the .htaccess you should not need any rewriting at all.
I believe the problem with the other answers, is that you were rewriting the location for a file, when it should be in the format of %{DOCUMENT_ROOT}%{REQUEST_URI}, so you might have an error handler sending you back to the home page. So check your error logs and access logs.