Forums

Redirecting to HTTPS with .htaccess file, I am missing two rules?

Hello. I know that PA advise to use NakedSSL service but I thought that I could get the same feature while using .htaccess file. The thing is, I have never done it before and I am not sure if I didn't mess something up.

At first I started with this code:

AddHandler application/x-httpd-php72 php
php_value memory_limit 256M
RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]

And I was happy because I thought it was working, I tested some basic address combinations and it was working.

But yesterday I got a warning from google search console about redirect problems and I panicked. I checked it and it seemed that this wasn't working:

https://example.com -> Not Secure Error Instead of https://www.example.com (since I read that it is best to decide on one type of www.)

I started searching and I tested several combinations and I ended up with this one:

AddHandler application/x-httpd-php72 php
php_value memory_limit 256M
# Canonical https/www
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

I tested it again and:

https://example.com -> 301 -> https://www.example.com Success!

BUT, I found 2 problems:

http://example.com -> 301 -> https://example.com -> 301 -> https://www.example.com - 2 redirects instead of 1? http://www.example.com -> 302! -> https://www.example.com - 1 redirect but 302 instead of 301?

And right now I am wondering if it could be done better? In my dreams, it should work that no matter of http/https/www combinations that I am doing I get ONE 301 redirect to https://www.example.com Is it possible to do? What am I doing wrong?

Where are you putting that .htaccess file? We use nginx rather than Apache, so that file isn't supported on our system -- you could create one, but it wouldn't do anything.

Hi. Yea, about that, I am also new to this .htaccess file. I am putting it on my domain server. I bought domain with another provider and I am putting .htaccess file in public_html folder. I need to further research what is best approach here to be honest.

But I see it taking effect, when I was experimenting not everything was working with redirect without my current settings.

We can't really give advice on how to set up Apache on a different service -- but perhaps someone at Stack Overflow would be able to help?

Sure, I will look over there. I am sorry for taking your time, I need to research it more :P