Categories
How To Servers Web

Redirect To SSL Using Apache’s .htaccess


There are plenty of times I want to require users to be accessing a site only via SSL. My first try at this was to simple create a .htaccess file that contained SSLRequireSSL, which basically tells Apache that access to a site can only be allowed if SSL is being used. This accomplished what I wanted, but it brought a side issue to requiring SSL, users often leave off (or forget) the the s in https. So after a little bit of digging around I found another approach to this. The new .htaccess file looks like this:

RewriteEngine On
RewriteCond %{SERVER_PORT} !443
RewriteRule (.*) https://www.example.com/require-secure/ [R]

The first line tells Apache we are going to use mod_rewrite. The second line only matches if the port being used to access the site is 443 (the port reserved for https use). If that second line matches then the third takes kicks in, which simply redirects the user to the SSL version of your URL. This still enforces the use of SSL, but saves you from trying figure why you can’t get to your site just because you forget the s in https.

UPDATE Tue 23 May 2006 @ 3:50pm : Comment #4 by Nicolás Echániz has an even better version of this that isn’t limited to checking a specific port (443) for SSL:


RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

73 replies on “Redirect To SSL Using Apache’s .htaccess”

I want my users to access their webmail through https, so I have this on my httpd.conf:

Alias /webmail “/var/www/localhost/htdocs/squirrelmail”

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
AllowOverride None
Options FollowSymLinks
Order allow,deny
Allow from all

Thank you SO MUCH! The mod_rewrite works great for me, I thought this problem was going to be more difficult to solve until i came upon this page. Now almost ready to launch our site.

I think you need to have a section set up to direct traffic to the SSL port with SSLEnable included in it.

I may also be full of crap. I’m kind of an Apache n00b.

Nicolás Echániz’

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

is very elegant, since it checks to see if it is using ssl regardless of what port is used and uses variables to do the rewriting. Good job 🙂

Thank all of you for your posts!!!
By combining Joseph Scott’s code and Joakim’s code into an .htaccess file at the root of my server files, I came up with:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*)https://www..com/index.htm

With your site in the middle of course… Works great! A user goes to mysite.com, and boom, it switches to http://www.mysite.com and is secure. Very nice!

I swear, every bit of these things is like chiseling a statue out of a block of marble. Each little bit requires a lot of hammering, but when you’re done…

Laters!

# htaccesselite Says:
October 24th, 2006 at 1:36 pm

I came up with a much better solution:

SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq “domaincom.secure.powweb.com”
AuthUserFile /www/d/domain/.htpasswd
AuthName “Private”
AuthType basic
require user admin56
ErrorDocument 403 https://domaincom.secure.powweb.com/private/index.php

Tutorial: http://www.htaccesselite.com/htaccess/force-https-and-no-double-login-vt30.html

Wow! That fixed my problem exactly! There is an even better SSL article at htaccesselite -> http://www.htaccesselite.com/htaccess/redirecting-all-or-part-of-a-server-to-ssl-vt61.html

Here is a most paranoid version that includes all the above comments. The idea is that we want to use a .htaccess file to make sure that all access to this directory will be by SSL or not at all, but we also want to make sure that if someone has typed a URL manually without the http/https, we direct to the desired url. The paranoid aspect of this lies in the fact that neither mod_rewrite nor mod_ssl might be available, say if you just ported to a new webserver setup etc.

# If we have neither mod_ssl nor mod_rewrite
# simply deny access

deny from all

# If we have mod_rewrite
# redirect to https version of requested page

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

# else (if we have mod_ssl)
# make sure we require SSL

SSLRequireSSL

# Finally, if anything went wrong, tell the user we
# require SSL
ErrorDocument 403 http://xyz.com/error-403-require-ssl.html

REPOST with edits because angled brackets got stripped out … replace all square brackets with angled brackets to make this work …

Here is a most paranoid version that includes all the above comments. The idea is that we want to use a .htaccess file to make sure that all access to this directory will be by SSL or not at all, but we also want to make sure that if someone has typed a URL manually without the http/https, we direct to the desired url. The paranoid aspect of this lies in the fact that neither mod_rewrite nor mod_ssl might be available, say if you just ported to a new webserver setup etc.

# If we have neither mod_ssl nor mod_rewrite
# simply deny access
[IfModule !mod_rewrite.c]
[IfModule !mod_ssl.c]
deny from all
[/IfModule]
[/IfModule]

# If we have mod_rewrite
# redirect to https version of page
[IfModule mod_rewrite.c]
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
[/IfModule]

# else (if we have mod_ssl)
# make sure we require SSL
[IfModule !mod_rewrite.c]
[IfModule mod_ssl.c]
SSLRequireSSL
[/IfModule]
[/IfModule]

ErrorDocument 403 http://xyz.com/error-403-require-ssl.html

Hi,

I have a page called test1.xml in /htdocs/test1/test1.xml and want to redirect to test2.php located in /htdocs/test2/test2.php using .htaccess file.
My entries are as follows in .htaccess :

Redirect 301 /htdocs/test1/test1.xml http://www.example.com/test2/test2.php

plz Correct me if any mistakes done in above line. I am using Apache 1.3.33 version.
I have created .htaccess file in /htdocs/ directory .
Let me know your suggestions

The “Update” with this code:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Works great. Any url from within my site automatically gets rolled to https:

My problem is that i only want ssl for authentication on a portion of the website (using htpasswd); after the authentication completed i want plain http back on. I am quite new at apache and i suspect i can use mod_rewrite.. but i failed to find any exemple to fit 🙁 thanks for any info

what if I have the following:

—————————————
NameVirtualHost *:80

ServerName webmail.mallavoodoo.com.br
Redirect permanent / https://webmail.mallavoodoo.com.br:443/

ServerName webmail.digiart.art.br
Redirect permanent / https://webmail.digiart.art.br:444/

NameVirtualHost *:443
NameVirtualHost *:444
listen 444

ServerAdmin suporte.provedor@ipad.com.br
DocumentRoot /mail/webmail
ServerName webmail.mallavoodoo.com.br
ErrorLog /var/log/httpd/webmail.mallavoodoo.com.br-ssl_error_log
CustomLog /var/log/httpd/webmail.mallavoodoo.com.br-ssl_access_log combined
SSLEngine on
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile /usr/local/etc/apache22/ssl/malla.crt
SSLCertificateKeyFile /usr/local/etc/apache22/ssl/malla.key

SSLOptions +StdEnvVars

SetEnvIf User-Agent “.*MSIE.*” nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0

ServerAdmin suporte.provedor@ipad.com.br
DocumentRoot /mail/webmail
ServerName webmail.digiart.art.br
ErrorLog /var/log/httpd/webmail.digiart.art.br-ssl_error_log
CustomLog /var/log/httpd/webmail.digiart.art.br-ssl_access_log combined
SSLEngine on
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile /usr/local/etc/apache22/ssl/digiart.crt
SSLCertificateKeyFile /usr/local/etc/apache22/ssl/digiart.key

SSLOptions +StdEnvVars

SetEnvIf User-Agent “.*MSIE.*” nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0

——————————————

when I try to access http://webmail.digiart.art.br/ ,

I get a a page with only:

SSH-2.0-OpenSSH_4.0

adn I don’t get redirected to https://webmail.digiart.art.br:444/

whats wrong? the purpose here is to use a certificate for each site.

Thanks

Never mind my previous post. I found the tweak.

Instead of:
Redirect permanent / https://…….

I wrote:
Redirect 301 / https://…….

and it worked !!

But thanks for letting me post here !

Hi to all, I m newbie to apache.

Can anyone explain to me wat is FollowSymLinks and Indexes FollowSymLink?

Do I have to put one of the above the under and under ?

I have put this into
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

in the .htaccess in the documentroot

the redirect is working but it is redirecting to the DirectoryIndex

etc -> http://www.abc.com/info.php becomes https://www.abc.com/
i want it to be changed to https://www.abc.com/info.php. How can i do that? what i ve done wrong?

@ Liew Jo Ee –

I’d suggest reading up on the DirectoryIndex option in Apache, which indicates that the default file name for a directory should be served as default if none is provided. In your example you’d do something like:

DirectoryIndex info.php

I edited my .htaccess file (added the text at the end of the htaccess file) and used Joakim’s and ChiselingStone’s points. (#s 10 and 11). It worked the first time. Thanks!

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Alot of people have written how to redirect http to https but nobody explains how to switch back to http. With apache once you switch to https it stays like that so what approach would you take to switch back to http from https?

I’ve been putzing with a ubuntu 7.10 server install, and having fits with most info I could find on removing directory listings, and also routing http to https sites.

My site has 4 normal virtual sites, and 1 self signed SSL site. I needed to have anything with http://some.secure.site route to https://some.secure.site.

All my other sites worked without problem, so http://www.somesite.com would resolve for all normal sites. but http://www.secure.site would drop back to the /var/www directory, meaning it wasn’t resolving to my /var/www/secure area. typeing in https://www.secure.site worked perfectly.

I liked the
[code]
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
[/code]
as listed above, but it wouldn’t work in a .htaccess. I turned on AllowOverride everywhere I could find it, but to no avail. I also installed (or it was already) the mod_rewrite and mod_alias was working too. I confirmed this by running phpinfo() and seeing that both were installed as loaded modules.

I finally removed it from .htaccess, and instead put it in the [Directory /var/www] section of /etc/apache2/sites-available/default.

Is working now.

Basically, all my named hosts resolve to their respective directories, but if someone puts a http: address that doesn’t resolve, it gets sent to my https://some.secure.site address. Seeing as how I only have one to worry about, it works fine.

For my directory listings, I tried the Options -Indexes in a .htaccess file, but no dice, kept giving 500 errors. I have error doc statements in .htaccess, and those work fine, so I new .htaccess is working.

I ended up going into the conf file for each site: http://www.somesite.com.conf under /etc/apache2/sites-available. In each site conf file, under the [Directory “/var/www/somesite”] section, i changed Options +Indexes to Options -Indexes.

That’s working too. So I removed both attempts from my .htaccess, as neither worked from that route. Instead I installed directives in the conf file for each site, and default, and it’s working fine.

simply create a squirrelmail.conf file at /etc/httpd/conf.d copy and paste below content, save it and restart APACHE

Alias /webmail “/usr/share/squirrelmail”

RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{HTTP_HOST}:443%{REQUEST_URI} [QSA,R=permanent,L]

[…] Editierlinks auf die ungesicherte Seite. Hier lässt sich mit einer .htaccess-Datei, welche ich auf Joseph Scott’s Blog gefunden habe, im Verzeichnis wp-admin Abhilfe […]

Hi,
Thanks for all your help above, i managed to put use what youve shared above and com eup with a solution that seems to work for me.

My problem is that i need to switch to ssl (https) for a particular directory based on using a shared host offering shared SSL.

The contents of the htaccess file i created was as follows:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} subdirectory
RewriteRule ^(.*)$ https://www.shared-ssl-domain-url.com/subdirectory/ [R,L]

PS – The htaccess file has to be stored in the sub directory you wish to use for ssl. E.g. subdirectory.

I hope this helps somebody.

I currently have my .htaccess file that sends all of the requests for my website to https: however I am trying to host two different sites under the same hosting. Well when I put in the URL then it redirects me back to the other site. Does anyone know the code to only redirect within the root directory and leave the subdirectories alone?

This is my current code:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq “example.com”
ErrorDocument 403 https://example.com

Thanks

To redirect a specific url to https use RewriteCond
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} =/secure #You can have multiple rewrite cond
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

To redirect the rest of the site from https to http:

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !=/secure
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Simple, elegant, works brilliantly.
THANKS!

I had to add [R=301,L] to my RewriteRule to get this working with wildcard subdomains.

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

I like the May 23rd updated solution best.
The problem with hard coding a redirect to something like http://site/something, at least for what I want, I just want to add https to whatever they typed. I don’t want to send them to a set home page but rather what they typed, just secure.
That’s why I like the first solution best.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Yay!
I don’t have to worry about where I put this or what site, as long as it has ssl enabled.

I’m using site without the www and this works well from root:
RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]

A subdirectory of my site is SSL that I want without the www too, but this does not work with another htaccess in the subdirectory:
RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^(.*)$ https://domain.com/subdirectory/$1 [R=301,L]

tried this too:
RewriteCond %{HTTPS} off
RewriteRule (.*) https://domain.com/subdirectory/$1 [R=301,L]

I just get the untrusted certificate warning at the www URL rather than the redirect.

TIA for any help

Hi guys,

Would the following rules have the effect as follows:

[code]http://mysite.co.za –> https://www.mysite.co.za[/code%5D

[code]Options +FollowSymLinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^mysite.co.za [NC]
RewriteRule ^(.*)$ https://www.mysite.co.za/$1 [L,R=301]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}[/code]

Just want to ensure that I can use the code in order to obtain the above dual result?

Thanks!

This is a really helpful post because I was constantly facing some problem in redirecting to SSL using apaches. You have explained everything in great detail with the requisite information in simple language. Thanks a lot!

I added an Exclude feature as well:

## This will switch any page from HTTP over to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

## This will switch from HTTPS back to HTTP on any page that has ‘travel-blog’ ‘easyblog’ in the URL
RewriteCond %{HTTPS} on
RewriteRule ^(travel-blog|easyblog)(.*)/?$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,NC,L]

Thanks a million. I’d tried loads of things and nothing worked – This got it sorted, you are a star 🙂

Hei thanks for sharing, that’s useful information for me. I’m going to buy SSL, but at first i must find out the way to configure that. ^_^ Keep sharing…

Hi,
I am very new at this, but please bare with me!
After using your redirect ( which is great),

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

it works however my sub-domain (blog) now goes in a loop back to the domain home page. I have tried several suggested exclusions for sub-domain, but haven’t been able to exclude it. Can you please help? I have a wildcard SSL

Greeting folks. I will make this short as possible. First, I want to thank everyone for their post.
I know absolutely nothing about coding or .htaccess files or anything else. I recently created an eCommerce site using OpenCart 2.0.1.0 and hosted it with FatCow. I purchased an SSL and learned in order for it to work with OpenCart I had to alter the config.php files at the root and in the admin folder << (To make the admin panel SSL also). After altering the files I had trouble with my website. I could add items to the cart but, when I clicked on any link it would log the user out. If I reversed the changes to the config files the website worked fine except it wasn't SSL. While as said I knew nothing about coding I did suspect it had something to do with links not directing properly due to the SSL. So, I thought, what if I could find a way to make all the pages SSL. Would that resolve the issue? I didn't know but, I aimed to find out. Then while searching I came across this site and decided to gamble by entering one of the codes above. This is the code I inserted.

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

Sure enough. This resolved the issue. Now my entire site is SSL and no more user log outs.

In short, thank all of you for posting your ideas and solutions. Now it's time to make some money with the site.. Thanks again 😉

Leave a Reply

Your email address will not be published. Required fields are marked *