Enforce https:// through .htaccess file?

Dopamin3

Gawd
Joined
Jul 3, 2009
Messages
870
I have a website built in React that never had an SSL certificate but now does. The host is using Apache.

The current .htaccess file (which works manually on http:// or https:// but doesn't FORCE https://) is:
Code:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

I tried just adding this to the top of the .htaccess file but browsers give ERR_TOO_MANY_REDIRECTS
Code:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

I'm derping on how to correct this.
 
A better way to do it is in your Apache site config if you are able to edit that. Something like this:
Code:
<VirtualHost *:80>
        ServerName mysite.com
        ServerAlias www.mysite.com
        ServerAdmin [email protected]
        Redirect permanent / https://mysite.com/
</VirtualHost>
<IfModule mod_ssl.c>
<VirtualHost *:443>
        ServerName mysite.com
        ServerAlias www.mysite.com
        ...
</VirtualHost>
</IfModule>
 
A better way to do it is in your Apache site config if you are able to edit that. Something like this:
I just have basic FTP access to the webhost, and I don't think I have a way to do that. I'd like to just achieve this through modifying the existing .htaccess file.
 
Maybe something like this?

Code:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
Header always set Content-Security-Policy "upgrade-insecure-requests;"

From: https://help.dreamhost.com/hc/en-us...r-site-to-load-securely-with-an-htaccess-file

There are also other examples on that link for other configurations and might help.
Those few examples didn't work. I'm getting closer from this and now my .htaccess is:

Code:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^.$
RewriteRule ^(.*)$ https://mywebsite.com/ [NC,L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [NC,L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ /index.html [NC,L,QSA]

This leads to mywebsite.com working (since browsers auto try https://mywebsite.com), https://mywebsite.com working, http://mywebsite.com properly redirects to https://mywebsite.com but still gives ERR_TOO_MANY_REDIRECTS (note: this is in incognito window so no cookies are stored)

1716557112564.png
 
Back
Top