在 apache 上强制使用 https

Force https on apache

我使用 Apache 服务器来发布我的网站。问题是我想强制我的网站使用 HTTPS。例如,如果有人输入 URL "http://www.alireza.co/contact.html" it should redirect to "https://alireza.co/contact.html".

我用这些规则创建了一个 .htaccess 文件:

# 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/ [R=301,L]

现在的问题是每当我输入 URL,无论是 httpshttp,还是 www. 或不输入,我都会得到错误 too many redirectsthe website is not redirecting properly 在 Firefox 中。

我使用 Autistici.org 作为我的主机提供商。我的网站是静态的(仅限 HTML/CSS)。我尝试了很多方法,但都没有成功。

我刚刚弄明白了。我唯一需要做的就是用这些简单的规则重写我的 .htaccess 文件:

# To remove www. from URL
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.alireza\.co [NC]
RewriteRule ^(.*)$ https://alireza.co/ [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

移除 www..htaccess 规则很简单,但我将其重定向到 https://alireza.co/ instead of http://alireza.co/$1.