Home > Software engineering >  htaccess turn on https and www BUT only when live, not locally
htaccess turn on https and www BUT only when live, not locally

Time:09-02

I would like to have .htaccess code that adds https and www to my URLs – but only when my site is live, not when I am developing locally on my computer.

I have the following

RewriteCond %{HTTP_HOST} !^localhost(?::\d )?$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(. )$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

But this doesn't appear to be adding the www when my site is live. So for example https://example.com doesn't have the www and all the links are broken. For example https://example.com/about just gets a 404 Not Found error message.

Thanks for any help. I don't understand .htaccess files/code.

EDIT / UPDATE

Comparing the code to other code, should it be the following?

RewriteCond %{HTTP_HOST} !^localhost(?::\d )?$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(. )$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

CodePudding user response:

Comparing the code to other code, should it be the following?

RewriteCond %{HTTP_HOST} !^localhost(?::\d )?$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(. )$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

Yes.

Your original rule explicitly removed the www subdomain. If you had requested http://www.example.com/ (note HTTP), you would have been redirected to https://example.com/ (HTTPS non-www). But nothing would happen if requesting https://www.example.com/ - the canonical URL (the rule is skipped because the 2nd and 3rd conditions fail).

The %1 backreference contains the match from the first capturing group in the preceding CondPattern. eg. Given the CondPattern ^(?:www\.)?(. )$ then %1 contains whatever is matched by (. ) (the first capturing group), ie. the hostname, less the optional www. prefix.

There is no difference between testing %{HTTPS} off or %{HTTPS} !on - the result is the same.

Test first with 302 (temporary) redirects to avoid potential caching issues. You will need to clear your browser cache before testing since the erroneous redirect will have been cached by the browser.

RewriteCond %{HTTP_HOST} !^localhost(?::\d )?$ [NC]

Checking for a port number would seem to be unnecessary here. This will fail if you are using localhost on the standard port (80 or 443) since the port number will be omitted from the Host header. Something like !^localhost would suffice, or perhaps !^localhost($|:) if you happen to using a domain name that starts localhost!

  • Related