Apache: Redirect http to https Apache secure connection – force HTTPS Connections

last updated in Categories Apache, Howto, Security, Tips

Let us say you have webmail sub-domain called http://mail.nixcraft.com and you would like to redirect it to https secure connection i.e. https://mail.nixcraft.com.


This will help you protect user privacy and sensitive information such as username and password remotely.

So how do you configure your Apache web server so that you prevent your web sites from being accessed without encryption?

Redirect http to https Apache Configuration

First make sure Apache is configured for HTTPS connection and necessary SSL certificates are installed.

No non-ssl access i.e. only accept https connections

Now open httpd.conf or .htaccess file (mod_rewrite not required):
# vi httpd.conf
Append following line :
Redirect permanent / https://mail.nixcraft.com/
Any request made to http://mail.nixcraft.com will goto https://mail.nixcraft.com/

Save and close the file. Restart the Apache:
# /etc/init.d/httpd restart

This is easiest way to ensure that your normal user never use plain text HTTP protocol to send data. Now this makes it much harder to sniff sensitive data.

Force webmail login over SSL https session

So if you want force users to access their webmail through https, add following configuration to .htaccess file:

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

Make sure you have something as follows in httpd.conf (mod_rewrite support):
LoadModule rewrite_module modules/mod_rewrite.so


Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

80 comment

  1. Not working for me. In Firefox I get:

    “Firefox has detected that the server is redirecting the request for this address in a way that will never complete.”

    I can see the location in the browser change to “https://…” but it just throws me that error.

    If i write the location directly it works fine.

    Thanks for any advice.

  2. You can’t do this in a virtual server that listens on both 80 and 443. It’ll redirect 80 (http) to the 443 (https) url, but then the https site will redirect back to itself if they’re both handled in the same virtual server block.

  3. I had the same experience as Luis on 5/3/2007, running on a LAN. Interestingly, when I then remove / disable the line with an `#’ like in:

    # Redirect permanent / https://ws530/

    redirection takes place as originally desired (in this case w/o any site certifications). In fact, I do not know how to revert back to communicate via http:// …

    What happened?

    1. You used a “permanent” redirect. Your web browser remembers the redirect forever, and will perform the redirect without interacting with the server.

  4. hi,
    i got s SSL for “secure.myurl.ext” and want the anybody accessing secure.myurl.ext sees the content from “myurl.ext” which is my main site, but i don’t want to do a redirect and URL above should remain as “secure.myurl.ext”
    so do i need to re-upload everything to my secure folder, or i need to do a mod_rerite trick.


  5. Hi there…

    I just tried adding # to disable the line and redirection takes place pretty straight-forward

    Strange… or this is a bug ?

  6. sandi… did you restart apache when you disabled the line?

    In my case, running the HTTPS on the same server as the HTTP, the mod_rewrite rules:

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

    In my webroot/.htaccess file are enough to redirect all http traffic to https.

    capcha: iptable — could also use these to do the https redirection πŸ˜‰

  7. Hi,
    I have used rewrite in my httpd.conf, but it doesn’t work.
    It shows this error :
    HTTP Status 405 – HTTP method GET is not supported by this URL

    How can I solve this problem?


  8. Where exactly within the httpd.conf file do you place the line ‘Redirect permanent / https: …’

    Thanks for the help.

  9. This way will never work. Instead go to the sites root directory. Open up .htaccess and add line

    RewriteEngine On
    RewriteCond %{SERVER_PORT} 80
    RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

    This should work

  10. if you want to remove redirect permanent, then hash the line where you have given redirect option.
    then restart the server, restarting the httpd sometimes doesn’t work.

  11. “if you want to remove redirect permanent, then hash the line where you have given redirect option.
    then restart the server, restarting the httpd sometimes doesnÒ€ℒt work.”

    My redirect is still active how do i fix this also i have my server running on port 5500 but this doesnt work /foo http://localhost:5500/bar why not?

  12. Thanks. Your second piece of advice (using RewriteEngine) was exactly what I was looking for. We just put https on a site following concerns over passwords being transmitted in the clear and this solves that issue in one fell swoop.

  13. I tried using this method for a server host site and everything works as it should except that the server statistics like load and uptime show as “Not Available”. These are the only two items that won’t show. Without the .htaccess file there, the server stats work fine from both http and https. I’m stumped.

  14. Hello guys, recently i purchased rapidssl from sslgenie. I used to redirect all my requests of http://nodewire.net/any url to https://nodewire.net/any url just by modifying .htaccess. this seemed to work well with SSLGENIE cert. However, when i switched over to Rapidssl cert, this edit in .htaccess seemed to be a problem. So i had to remove the code in htaccess, now my site has https only when a user manually types it. Please tell me how to redirect all http requests to https by editing httpd.conf or .htaccess.

    PS: Rapidssl has a server root certificate while sslgenie doesnt! though this might help a bit?? (dunno)

  15. using: apache2-mpm-prefork 2.2.9-10+lenny2 on Linux Debian

    1.) I have been trying for days to get redirect/force to only https without success.
    I too get loop error if I add the line to apache2.conf:
    Redirect permanent / https://my.domain.com/
    2.) I’ve also tried both .htaccess codes posted above creating a .htaccess and put it in webroot /var/www/.htaccess (I presently don’t use any .htaccess files)
    “Internal Server Error <The server encountered an internal error or misconfiguration and was unable to complete your request…..”

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

    chmod 644 /etc/apache2/.htaccess
    /etc/init.d/apache2 reload

    ============also tried:
    RewriteEngine On
    RewriteCond %{SERVER_PORT} 80
    RewriteRule ^(.*)$ https://myurl.com/$1 [R,L]

    same error
    3.) Another place I read to add this line to apache2.conf:
    LoadModule rewrite_module modules/mod_rewrite.so

    Cannot load /etc/apache2/modules/mod_rewrite.so into server: /etc/apache2/modules/mod_rewrite.so: cannot open shared object file: No such file or directory

    This prevented my apache from restarting as suspected as I can’t find in ‘any’ of the files the “LoadModule” line, period.

    The only thing I could find that sounds related was this here:
    so seems this module isn’t even loaded as it’s not in the /mods-enabled/ directory.

    Please if anyone could help solve this that would be great!
    Thank you for your time πŸ˜€

  16. Forgot to post this part as well:

    4.) Also read to do this and get error:
    pico /etc/apache2/sites-available/default
    Was this:

    ServerAdmin webmaster@localhost

    DocumentRoot /var/www/

    Changed to:

    ServerAdmin webmaster@localhost
    RewriteEngine on
    RewriteRule ^/(.*) https://myurl.com/$1

    DocumentRoot /var/www/

    /etc/init.d/apache2 reload
    Syntax error on line 3 of /etc/apache2/sites-enabled/000-default:
    Invalid command ‘RewriteEngine’, perhaps misspelled or defined by a module not included in the server


  17. I was able to get a HTTP to HTTPS redirect working.

    I put the redirect permanent in httpd.conf, in the section for a specific NameVirtualHost listener:

        ServerName mywebsite.com:80
        ServerAlias www.mywebsite.com:80
        Redirect permanent / https://www.mywebsite.com/

    – Matt H
    – IntuitLabs.com

  18. Awww… it removed the gt/lt symbols…. {VirtualHost} and {/VirtualHost} surround the command below the NameVirtualHost…

    1. @Matt,

      I’ve edited and escaped your configuration. The key is to put commands in config in pre / code tag.


  19. I have a requirement of such that, need to forward https request to http based on the path.

  20. Sorry the question was not clear, again:

    I have a requirement of such that, need to forward https request to http based on the path. Any ideas, how to implement in in Virtualhost ?


  21. I am a squat on advanced Apache work. I would get a basic SSL functionality to work.
    So https://foobar.com works fine and gets me all the login windows I designed. however currently all the images and other extensions like .pdf are also using the https routing.
    some image referred on that https link
    e.g. https://foobar.com/loginhere.jpeg c
    can be displayed using https but not http
    I would like to JUST limit https usage to the login window html and ALL other images pdf’s and unsecured html ( ones that do not need password ) should use HTTP NOT HTTPS
    any idea how that is done ?
    any idea how I can find out which particular filetypes are being redirected via https
    Thanks for your help

    1. Hi Sam,

      Did u get the solution for your http to https limited links

      i need the same pelase do suggest me how to do that

      thanks in advance

  22. hi,
    I want to redirect
    http://myserver.com/my_app/login.htm to
    (only the login page) I tried various combination but it didn’t redirect. It will be a great help if some one can help.

  23. Hey guys,

    those having problems in form of a redirect did not take place,
    did you do a
    /etc/init.d/apache2 force-reload
    Actually that should only be necessary if you write it into the httpd.conf or a virtual-host-description file. when using .htaccess it should work right away…

    worked fine for me

    best regards

  24. Is it possible to have ALL sites hosted on an apache server redirect to an HTTPS:// address?

    instead of posting each one individual….

    1. Well have you tried using an http meta-redirect, or using .htaccess in the subdirectories, so that app1 is always https while app2 is always https, they have tutorials out there, try using meta-redirect in an index.html page, that way if you screw up you can always make a new index.html page, and not fuss around with .htaccess, its easy writing html code but not .htaccess…

  25. The answer is surprisingly in another tutorial on the site.

    In the directory you want to redirect to ssl:

    SSLRequire %{HTTP_HOST} eq “www.nixcraft.com”

    I have this under my document root in httpd.conf and it works great. I have the virtual host in ssl.conf set up to use the same directory. works great

  26. Hi,

    I have installed SSL certificates and now I want to move from http to https.
    what should I do?
    should I need to move my all files to https folder ?


  27. Redirect permanent did not work at all. Tried it inside and outside of the virtual host.

    Do more research next time

  28. Agh! Do what SCD says!

    RewriteEngine On
    RewriteCond %{SERVER_PORT} 80
    RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
  29. Dows anyone have any idea please on what lines of code that I’m going to add into the htaccess file? Basically, I just need my login page, registration page to be in SSL. The rest of the pages will be in http like the index.php. I have the SSL installed already in my server. I have the htaccess code to redirect all pages into https but I don’t need the whole site to be in https. I have this few lines of code and this make the whole site in https:

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

    I need only these pages to be https and the rest of the site to load in http


    Any idea please on how to make it that only login, registration to be in https? Then if user open it in http it will automatically be redirect into https. If user open index page in https it will automatically be change into http. Please help.

    1. try this

      RewriteCond %{REQUEST_URI} ^?do=login [OR]
      RewriteCond %{REQUEST_URI} ^?do=reg [OR]
      RewriteCond %{REQUEST_URI} ^?do=login&url=sell [OR]
      RewriteCond %{REQUEST_URI} ^?do=login&url=myaccmain [OR]
      RewriteCond %{REQUEST_URI} ^?do=login&url=sindex [OR]
      RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  30. Hello,

    there are a lot of domains hosted in my dedicated server.
    There is an alias /webmail pointing to the installed webmail-interface which could be used from all domains on my server

    e.g. there are the domains foobar1.de, foobar2.net, foobar3.com, foobar4.de, foofoobarbar.info, Ò€¦
    and the webmail client is reachable: e.g. foobar1.de/webmail , Ò€¦ , foofoobarbar.info/webmail

    That’s fact and running.

    Now i want to force all “/webmail”-calls to “https://”, so that the call “foobarxy.org/webmail” automatically chanches to “https://foobarxy.org/webmail” without regarding other calls like foobar.org (homepage) oder foobar3.com/directoryxy or others.

    The aim is to force only the “/webmail” calls to htts not the others.

    Is there a simple way?

  31. This worked for me, using apache2 and 2 virtual hosts:

    1. Type the following command in the terminal:

    sudo a2enmod rewrite

    Add the following to /etc/apache2/sites-available/default under

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

    Restart Apache:

    sudo /etc/init.d/apache2 restart
    1. What i want to achieve is configure outbound proxy for specific HTTPS urls. Its a white list validation. e.g. If i (my application) hits a specific HTTPS URL , then only redirect should happen .. something like this –

      RewriteCond %{THE_REQUEST} ^GET (http://www.google.com/.*) HTTP [OR] RewriteCond %{THE_REQUEST} ^GET (http://www.oracle.com/.*) HTTP RewriteRule . proxy:%1 [L]

      RewriteCond %{THE_REQUEST} ^CONNECT (www.abc.com):443/?.*) HTTP RewriteRule . proxy:https://%1 [L]

      The first part for HTTP works fine. So outbound URLs which start with HTTP gets redirected according to rule but if i hit HTTPS , it doesnt work .. it gives forbidden error or cookie error..

      Can any body please help.

  32. Hi my site has SSl installed.
    I want all www and non www http traffic to redirect on https://www. version
    I used the above code

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

    But my innerpages also get redirected to home page please help.

    FYI: I am using Drupal+Ubercart

  33. Hi Sudeep just paste this code:

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

    in .htaccess under the

    # To redirect all users to access the site WITHOUT the ‘www.’ prefix,
    # (http://www.example.com/… will be redirected to http://example.com/…)
    # uncomment the following:
    # RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
    # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

    After that, it will work.

  34. Is there anyway I can redirect

    http requests to http
    https request to https

    I mean through redirect/rewrite rules?

  35. If you want to have a redirect from HTTP->HTTPS but not for a specifice subfolder (eg for images) then you could use the following rewrite rules:
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteCond %{REQUEST_URI} !.*/img/.*
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    in this example it will redirect every request to HTTPS if it is not HTTP and has not /img/ in the URL.

  36. Hi,
    I want to do some redirections like this:
    base-url.com -> base-url2.com (but only if no subdir is given)
    base-url.com/any_subdir -> https://base-url.com/any_subdir
    and, if possible, this rulsets only within the site-config not within .htaccess, cause there are developers cleaning folders… this is driving me nuts…
    I can’t get it. Can anyone give me a hint, please?

    1. Sorry, my initial description was to short.

      What I need to do is, to do two redirects on one base-url with two different conditions. First is to redirect a request with just the base-url (like _http://some_url.org) to _http://some_other_url.org .

      _http://some_url.org -> _http://some_other_url.org

      The second one is, if _http://some_url.org/some_subdir is requested it shoud be redirected to SSL of the same host _https://some_url.org/some_subdir .
      So in case 2 it should not be redirected to some_other_url.org .

      _http://some_url.org/some_subdir -> https_://some_url.org/some_subdir

      Both rewrites are not verry complex for its own, but I can’t get them working together.
      So my problem is, how do I have to set the RewriteCond (to be exact the regexp) to do the matching. The http->https overrules always.

      I did several experiments with RewriteCond, RewriteRule, RedirectMatch but I didn’t get it. Does anybody have an idea?

      Oh, btw this should be done by the vhost-config, not with .htaccess-files in document-folders. It’s a restriction I’m not responsible for πŸ™ cause developers sometimes empty the doc-folders.

      Sorry, I had to do this _http because of this editor to not recognize this “URLs”.
      thanks a lot

      best regards, M.

  37. I have enabled https and also able to navigate application using http and https without rewrite. Apache 2.2.24. but see a strange behavior.

    Receiving 400 bad request if passing http://hostname.com/webapp-name but works fine with http://hostname.com/webapp-name/ don’t know how / can help to redirect to https.

    Also, enabled the rewrite with following in httpd.conf but don’t see a difference.
    Also, http redirection is going improper. Please help me as today is my submission

    # Rewrite Engine
    RewriteEngine On
    # now the rewriting rules
    RewriteCond %{SERVER_PORT} !^443$
    RewriteRule .* https:///webapp-name [R,L]

    1. SetHandler weblogic-handler

      WebLogicHost 10.95.XX.XX
      #MatchExpression *.jsp
      #MatchExpression *.html
      Debug ALL
      DebugConfigInfo ON
      WLLogFile c:/weblogictemp/projectname.log
      WLTempDir c:/weblogictemp

      SetHandler weblogic-handler
      WebLogicPort 7003

      SetHandler weblogic-handler
      WebLogicPort 7005

  38. Based on user clicks on language browser redirects to specific language….i18N support


    RewriteEngine on
    ## Rewriting url for ARabic support browser
    RewriteCond %{HTTP:Accept-Language} ^ar [NC]
    RewriteRule ^/ProjectName/$ [L,R=301]

    ## Rewriting url for EN english supports browser
    RewriteCond %{HTTP:Accept-Language} ^en [NC]
    RewriteRule ^/ProjectName/$ [L,R=301]

    Have a question? Post it on our forum!