Reputation: 9
I have a multi site where the sub pages should redirect from non-www to www.
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^/?$ "https\:\/\/www.example\.com" [R=301,L]
This code above works if you enter https://example.com
, then you are forwarded to https://www.example.com
. But if you go directly to a subpage such as https://example.com/about
, then you aren't redirected to https://www.example.com/about
.
How do I write the redirect to fix this?
I have tried different redirects but I can't get them to work.
Upvotes: 1
Views: 24
Reputation: 42935
Well, i your rule you explicitly only match requests to the root path (/
) by your pattern ^/?$
. That pattern will obviously only match an empty string or a string with a single slash in it and nothing else.
So you need to change that such that the rules gets applied to all requests and that the requested path is preserved in the rewriting step:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^ https://www.example\.com%{REQUEST_URI} [R=301,L]
An alternative you often see is the following. It does not really make sense in your specific situation where you want to rewrite all requests to the "www" variant of your domain. But it might allow for more flexibility if you need to tell apart different requests for specific purposes (like requests to an API versus requests for the UI):
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^/?(.*)$ https://www.example\.com/$1 [R=301,L]
Upvotes: 1