I want to redirect any traffic that goes to http://example.com to https://example.com
same for http://example.com/about to https://example.com/about
I though
According to the Apache documentation, using mod_alias
is more appropriate than mod_rewrite
for this task. That is, in order to redirect all HTTP traffic to HTTPS, one would:
<VirtualHost *:80>
ServerName www.example.com
Redirect permanent / https://www.example.com/
</VirtualHost >
<VirtualHost *:443>
ServerName www.example.com
# ... SSL configuration goes here
</VirtualHost >
Two things to note about this configuration:
VirtualHost
directive is only valid in the "server config" context.mod_rewrite
directives are processed before mod_alias
directives. If you've already got a massive block of RewriteRule
s in your .htaccess
file, you might be better off with the mod_rewrite
configuration.This works for me:
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
If the traffic is coming in over non-SSL HTTP, then redirect to the HTTP equivalent of whatever page the user was originally trying to access. It also doesn't involve any mod_rewrite options, so it's easy to read.
Side rant: why does everyone feel the need to explicitly set the HTTP code of the redirect and mark one of their rewrites as the "last" one? Seriously, I've seen dozens of same-looking htaccess rules in just the last few days.
Working in all conditions is:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
<IfModule>
This is a previous answer using .httaccess but adding changes proposed in the comments, and some from me:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://my.domain.name%{REQUEST_URI} [L,R=301]
Notes:
%{HTTPS}
is not set to off
when using http, but is null, so !on
is more reliable rule than off
.%{SERVER_NAME}
. If you consider using that, check out caveat from this discussion - it relies on other configuration being correct.R=301
means it's permanent redirect, as it's usually meant to be in this case. If you instead think it's temporary, that can be left out or specified as R=302
.L
means it's last rule to be applied for this request. Leave it if you suspect or know there are other rules after this that you don't want to get applied. You can remove if this is the only rule of the file.why not just plain and simple?
rewriteCond %{HTTPS} !on
rewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
it has worked to me, and seems to me clear. Cheers.
After some research this what worked for me, a bit different version.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]