Abhishek Tirkey
Abhishek Tirkey

Reputation: 455

Apache2 - Resolving redirect to https

Even after trying several solutions, I'm trying to force HTTPS redirect on my website via the following configuration in the site's .htaccess file:

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

However, it's resulting in the error of too many redirects. I came to suspect this may be either because of the the HTTPS flag not being set or port number not switching to 443 on specifying https in the browser - as on outputting the port number via PHP, i.e, $_SERVER['SERVER_PORT'] it still shows 80. My .conf files were set up according to what I came across on what seemed to be reliable sources.

Any insights into how I can get this resolved would be appreciated.

Upvotes: 1

Views: 33

Answers (1)

poncha
poncha

Reputation: 7866

Apache foundation suggests to avoid using mod_rewrite for this type of problem when possible.

You should use mod_alias Redirect directive instead.

<VirtualHost *:80>
ServerName www.example.com
Redirect "/" "https://www.example.com/"
</VirtualHost>

<VirtualHost *:443>
ServerName www.example.com
# ... SSL configuration goes here
</VirtualHost>

However, in cases where You are limited to .htaccess only and cannot alter vhost/main configuration files, You can do this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule . https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

Upvotes: 1

Related Questions