在Apache上强制使用https

时间:2019-02-15 19:42:14

标签: apache .htaccess ssl https no-www

我使用Apache服务器发布我的网站。问题是我想强制我的网站使用HTTPS。例如,如果有人输入URL“ http://www.alireza.co/contact.html”,则应将其重定向到“ 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/$1 [R=301,L]

现在问题出在我输入URL时,无论使用httpshttp还是使用www.或不使用它,都会出现错误too many redirects或{ {1}}在Firefox中。

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

1 个答案:

答案 0 :(得分:1)

我只是想通了。我唯一要做的就是用以下简单规则重写我的.htaccess文件:

# 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

使用简单的.htaccess规则删除www.,但我将其重定向到https://alireza.co/ $ 1而不是http://alireza.co/ $ 1。