Reputation: 25
I am coding a React app which I deployed on my webserver. I have the following .htaccess file which servers all requests via the index file because I am using client sided routing:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
which works.
I would however want to redirect all traffic to HTTPS non-www. Could someone guide me in the right directions using the standard .htaccess file but via index.html:
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]
Upvotes: 0
Views: 915
Reputation: 1397
Easiest to break down what you already have (which does the opposite)
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
Matches when the request is not done through https... pretty simple. The [OR] at the end means that either this rule or the one below it must return true.
RewriteCond %{HTTP_HOST} !^www\. [NC]
this matches if there's no "www." at the start of the request (^
means the start, !
means "not"). [NC]
means "nocase" so basically just ignores the case. Not necessary on linux servers but still recommended.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
So once either HTTPS is off or the string doesn't start with www.
, the HTTP_HOST is passed into this rule. This rule will always return true as the regex matches an OPTIONAL "www." (because of the ?
after the paren), then one or more and character (.+
) until the end of the string ($
).
The .+
part after the optional www.
is wrapped in parens to capture it ( (?:
before it signifies a non-capturing group, so the rest of the host name is captured as %1
- or the first captured group).
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]
This then rewrites the request, to include https://www.
plus the rest of the host name $1
and then the REQUEST_URI, which is everything from the first /
in the URI.
The bit at the end of the rule is also pretty simple, L
means this is the last rewrite rule, NE
means noescape
- this is useful when including the request_uri to prevent it being escaped. R=301
means redirect with a 301 status.
TLDR - Your solution
So to create the rule that you need to drop the www., you should flip a couple of those options:
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
On the second RewriteCond
we remove the !
to make it match a url that DOES start with www.
, then on the RewriteRule
we remove the www. that's being added in.
Upvotes: 3