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}

58 Comments

  1. You can also add the following to a .htaccess file:

    SSLRequireSSL

    #no non-ssl access
    Redirect permanent /secure https://www.example.domain.com/secure

    PS. I’m LDS too!

  2. Dang…forgot the code tag…

    SSLRequireSSL

    #no non-ssl access
    Redirect permanent /secure https://www.example.domain.com/secure

  3. i use SSLRequireSSL in my .htaccess file and it causes a server error any ideas?

  4. Nicolás Echániz

    Sat 4 Dec 2004 at 6:07 pm

    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

  5. I find that the following works

    IfModule !mod_ssl.c>
    # no non-ssl access
    Redirect permanent / https://www.cse.unsw.edu.au/
    </IfModule>

    from http://www.cse.unsw.edu.au/faq/questions/www-htaccess.html

    PS moderator pls deleted previous post the <’s were striped

  6. 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.

  7. Thanks, exactly what I was looking for; works great.

  8. I have uploaded a .htaccess file to my root with the code that is posted in the original article. When i try to access the folder http://www.example.com/require-secure it brings me to https://www.example.com/require-secure straight away but it also throws out a 404 error. I’m wondering if anybody knows why this might be happening?

  9. 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.

  10. 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 :)

  11. 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!

  12. My non-mod_rewrite solution:

    ServerName example.com

    RedirectPermanent / https://example.com/

    ServerName example.com

  13. Sorry, tags are not escaped but stripped. I’ll use square brackets:

    My non-mod_rewrite solution is:

    [VirtualHost *:80]
    ServerName example.com
    [Location /]
    RedirectPermanent / https://example.com/
    [/Location]
    [/VirtualHost]
    [VirtualHost *:443]
    ServerName example.com
    [/VirtualHost]

  14. Just a note: I couldn’t make this work until I realised that HTTPS env variable was not available in my web server, God knows why. I had to use the SERVER_PORT solution instead.

  15. hi

    how to redirect http to https,

    what data has been put in the htaccess file

  16. How can I change my login page and other personal information page from http to https?

  17. 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

  18. # 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

  19. Rudolf Potucek

    Tue 7 Nov 2006 at 7:13 pm

    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

  20. Rudolf Potucek

    Tue 7 Nov 2006 at 7:18 pm

    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

  21. According to http://www.askapache.com/2006/htaccess/apache-ssl-in-htaccess-examples.html you don’t need mod_ssl to check for HTTPS variable.

    [IfModule !mod_ssl.c]
    deny from all
    [/IfModule]

    And I think if HTTPS isn’t on its empty?

  22. Are the IfModules even correct syntax? Are you allowed to use them? How come there aren’t any at the http://www.askapache.com/2006/htaccess/htaccesselite-ultimate-htaccess-article.html ?

  23. 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

  24. 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:

  25. Jarrod I still get a warning if I try to goto http://www.site.com:80

    The only way to make sure my site doesn’t act funny and popup warnings is to use the SSLRequireSSL with the erordocument suggested by ti89..

    http://www.askapache.com/2006/htaccess/apache-ssl-in-htaccess-examples.html

  26. 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

  27. 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

  28. 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 !

  29. I used Jarrod’s code from 2/13/07 and it’s perfect. Many thanks :)

  30. 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?

  31. @ 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

  32. I was looking for this snippet of code for one of my customers thanks a million!

  33. @Kyle -

    Cool, always nice to hear people find this stuff useful.

  34. 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}

  35. 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?

  36. 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

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

    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.

  37. If you want HTTPS for only 2 or more individual files not a full directory, Then try this

    RewriteEngine On

    RewriteCond %{SERVER_PORT} !^443$
    RewriteRule ^index.php$ https://www.phppassion.com/index.php

    RewriteCond %{SERVER_PORT} !^443$
    RewriteRule ^index1.php$ https://www.phppassion.com/index1.php

    It works.

  38. if anyone want to full directory HTTPS

    Try this

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

  39. 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]

  40. thanks! works great, nice and simple!

  41. 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.

  42. 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

  43. Boy am I late to the party on this, but thanks! I spent hours looking for code that would work and this did the trick.

  44. worked for me – thanks!

  45. 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]

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

    Simple, elegant, works brilliantly.
    THANKS!

  47. 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]

  48. I am sorry to tell you, that those examples won’t work if you are on a non standard http port, e.g. http://www.example.com:8888/ will redirect to https://www.example.com:8888/

    use this instead:

    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{SERVER_NAME}%{REQUEST_URI}
    
  49. 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.

  50. You can do a classical redirect in apache conf.

    Redirect / https://mypage.com/

    I have another question.

    How do exclude certain pages from being redirected to https?

    Thanks

  51. 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

  52. Hi guys,

    Would the following rules have the effect as follows:

    http://mysite.co.za --> https://www.mysite.co.za
    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}

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

    Thanks!

  53. I’m a real novice. Where do I put this code?

  54. It can go directly in your Apache config file, or in an .htaccess file (assuming your Apache setup has them enabled).

  55. Vanity mirrors seattle

    Wed 21 Nov 2012 at 11:20 am

    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!

  56. E. D. Dickenson

    Thu 24 Jan 2013 at 10:53 pm

    RewriteCond %{HTTPS} !=on
    RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]

  57. 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]

  58. Better use: (without code tags…)
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2014 Joseph Scott

Theme by Anders NorenUp ↑