Multiple working methods for http to https Redirect using htaccess in Apache, Linux. Check all the solutions here. Find the best solution for your Server environment.
Redirection from http to https
If you want to redirect all traffic from http to secured https url using 301 or permanent redirection, then try the following code on the top of your .htaccess file located on the root of your website.
RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
For some host, in additional to the above code, you need to add the following code on the top of all .htaccess codes.
RewriteEngine On
Redirect behind load balancers or Nginx Reverse Proxy
RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
http to https Redirect htaccess Sample Code Screenshot Image
Common Problems – Redirection from http to https
Problem 1: http to https redirection does not work with .htaccess file. What’s the solution ? When loading the page with http, the .htaccess redirect URL to https but when loading the page with https, there is an infinite loop.
Solution 1: You might be using Nginx as a reverse proxy along with apache or might be behind a load balancer. So try to use the above htaccess code for Redirect behind load balancers or Nginx Reverse Proxy.
Problem 2: apache HTTP:X-Forwarded-Proto in .htaccess is causing redirect loop in development environment, but working fine in live or production environment.
Solution 2: To make it work in both development and production environments you can combine both conditions like given below:
RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteCond %{HTTPS} off RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
Problem 3: Special case for a shared hosting. If everything given above is not working, then try the following solution.
Solution 3: http to https redirection using .htaccess file using port number
RewriteCond %{HTTP:X-Forwarded-Port} !443 RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Comments and Discussions