apache.htaccesssslhttpsno-www

Force https on apache


I use Apache server to publish my website. The problem is I want to force my website use HTTPS. For example, if someone enters the URL "http://www.alireza.co/contact.html" it should redirect to "https://alireza.co/contact.html".

I created a .htaccess file with these rules:

# To use 404.html as default 404 error page.
ErrorDocument 404 /404.html


# To force website use https and remove www. subdomain.
RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://alireza.co/$1 [R=301,L]

The problem is now whenever I enter the URL, no matter with https or http, or with www. or without it, I get the error too many redirects or the website is not redirecting properly in Firefox.

I use Autistici.org as my host provider. My website is static (HTML/CSS only). I tried a lot of howtos but I had no success.


Solution

  • I just figured it out. The only thing I had to do was rewriting my .htaccess file with these simple rules:

    # To remove www. from URL
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www\.alireza\.co [NC]
    RewriteRule ^(.*)$ https://alireza.co/$1 [L,R=301]
    #To force HTTPS
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    
    # To make 404.html default 404 error page
    ErrorDocument 404 /404.html
    

    It's simple .htaccess rules to remove www. but I made it to redirect to https://alireza.co/$1 instead of http://alireza.co/$1.