Force Ssl/Https Using .Htaccess and Mod_Rewrite

Force SSL/https using .htaccess and mod_rewrite

For Apache, you can use mod_ssl to force SSL with the SSLRequireSSL Directive:

This directive forbids access unless HTTP over SSL (i.e. HTTPS) is enabled for the current connection. This is very handy inside the SSL-enabled virtual host or directories for defending against configuration errors that expose stuff that should be protected. When this directive is present all requests are denied which are not using SSL.

This will not do a redirect to https though. To redirect, try the following with mod_rewrite in your .htaccess file

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

or any of the various approaches given at

  • http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html

You can also solve this from within PHP in case your provider has disabled .htaccess (which is unlikely since you asked for it, but anyway)

if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
if(!headers_sent()) {
header("Status: 301 Moved Permanently");
header(sprintf(
'Location: https://%s%s',
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
));
exit();
}
}

Forcing SSL and WWW using .htaccess

That's a bit simpler.

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]

Laravel: how to force HTTPS?

You need adding this to your .htaccess file:

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://YOURWEBSITEDOMAIN/$1 [R,L]

See this:
http://www.inmotionhosting.com/support/website/ssl/how-to-force-https-using-the-htaccess-file

Using 'mod_rewrite' how do I force HTTPS for certain paths and HTTP for all others?

You can put something like this in your :80 vhost:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(panel/|store/payment) https://%{HTTP_HOST}%{REQUEST_URI}

And this in your :443 vhost:

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule !^(panel/|store/payment) http://%{HTTP_HOST}%{REQUEST_URI}

http to https through .htaccess

Try the following:

 RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

Also, you can also redirect based on port number, for example:

 RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

This will redirect all requests received on port 80 to HTTPS.



Related Topics



Leave a reply



Submit