How to switch to/from HTTPS using Apache as a proxy to Tomcat

I’m writing this down because it too me an age to figure out a way of doing this. I have a website which Tomcat is happily serving. Areas of the site require a secure connection so I’m using Spring security to require particular URLs to be accessed over HTTPS. It means that when I access http://example.org:8080/webapp/login, it’ll bump me to https://example.org:8443/webapp/login. Note: Tomcat is setup with the SSL connector and a self signed .keystore see (http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html).

I have two vhosts setup in Apache, one for the http://example.org and one for https://example.org. They are both using mod_proxy to ProxyPass and ProxyPassReverse requests to the appropriate Tomcat URL’s. The problem comes when switching to HTTPS from HTTP and vice versa. Ideally I wanted some sort of ProxyPassReverse declaration in my config for http://example.org what would change HTTP headers (that Spring sets) for https://example.org:8443/webapp into https://example.org. Except ProxyPassReverse doesn’t work like that.

Now, I realise I could simply not use Spring to manage which parts of the site should be accessed over HTTPS and which should not…and just setup Apache to redirect as appropriate. I don’t want to do that though, because that makes the task of adding these restrictions a deploy time task, rather than a development time task. I don’t want to risk someone forgetting to add new restrictions when deploying the webapp and I’d much rather the developer added these restrictions when they were working on the task and really thinking about where and when they are needed.

So, how do I solve the problem so that the app can manage its secure-ness and I can setup Apache once and forget about it? The answer is to ProxyPassReverse onto a “special” URL, which when accessed will redirect to the HTTPS (or HTTP) site. For example, if the HTTP site needed to redirect to the HTTPS site, I’d add rules like so to perform the redirect:

    # Proxy a request (from the server) to switch to https onto a special URL "/2https/"
    ProxyPassReverse /2https/ https://example.org:8443/webapp/

    # When a client requests a URL prefixed with "/2https" map it onto the secure site
    RewriteRule ^/2https/(.*)$ https://example.org/$1 [R,L]

…and you’d add something similar to the secure site Apache config. As long as I don’t mount any pages at /2http or /2https I should be ok. Note a couple of things:

  • You’ll need “SSLProxyEngine on” and “RewriteEngine on” and obviously the appropriate Apache modules loaded for these commands.
  • Because of the redirect between HTTP <-> HTTPS you won’t be able to POST data between them directly (I’m not sure why you’d NEED to though)
  • Obviously you’ll need to setup Apache with an SSL certificate…but that is a different story

I should say a special thanks to this random site – from whence the idea actually came from. If anyone has any better ideas on how to do it I’d love to hear them. Please comment below.

12,022 thoughts on “How to switch to/from HTTPS using Apache as a proxy to Tomcat

  1. My brother suggested I may like this web site.
    He was once entirely right. This post truly made my day.
    You can not believe simply how much time I had spent for this information! Thank you!

  2. Hi would you mind stating which blog platform you’re working with?
    I’m going to start my own blog soon but I’m having a hard time making a decision between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different then most blogs and I’m looking
    for something completely unique. P.S My apologies for getting off-topic but I
    had to ask!

  3. Реконструкция старой кровли — сняли старый шифер уложили металлочерепицу. Дом сразу преобразился внешне. Соседи не узнали дом когда приехали в гости через месяц после работ. металлочерепица 0.5 мм Красноярск

  4. A retenção urinária aguda é uma complicação
    potencialmente complicado, caracterizada na incapacidade de urinar,
    mesmo com a bexiga cheia. A terapia combinada elimina rapidamente os sintomas e, ao mesmo tempo, elimina o tamanho da próstata a
    comprido prazo. Eles afetam principalmente o trato urinário inferior
    e podem progredir durante o tempo, causando desconforto e complicações.
    Como vimos, esses sintomas, conhecidos coletivamente como sintomas do trato urinário inferior
    (LUTS, pela sigla em inglês), são capazes de piorar progressivamente se não forem tratados.
    Esse desenvolvimento elimina progressivamente o calibre
    da uretra, dificultando a passagem da urina. Esse
    problema ocorre devido à obstrução causada pelo acrescento da próstata, que comprime a uretra e dificulta
    a passagem da urina. A ausência de atividade física assim como é um ingrediente agravante, uma vez
    que favorece para o ganho de peso e o acrescentamento da
    inflamação no organismo. Estudos bem como sinalizam pro papel da
    inflamação crônica e da hipersensibilidade do sistema nervoso periférico pela progressão
    da HPB. Dois hormônios em especial desempenham um papel importante: a testosterona e o estrógeno. https://Vibs.me/g1-xtragel-funciona-anvisa-composicao-preco-valor-comprar-resenha-farmacia-bula-reclame-aqui-saiba-tudo-2024/

  5. Post writing is also a excitement, if you be familiar with after that you can write or
    else it is difficult to write.

  6. По теме “Актуальная аналитика и новости России и мира”, там просто кладезь информации.

    Смотрите сами:

    https://journalrub.ru

  7. Отличная статья для тех, кто хочет понять, почему SEO — это не просто набор технических действий, а реальная стратегия роста в конкурентной среде. Автор разбирает ключевые элементы: анализ ключевых слов, оптимизацию контента, техническую базу и внешние факторы. Отдельно радует блок про локальное SEO для регионального бизнеса. Рекомендую: https://bioice-krasnoyarsk.ru/stati/seo-kak-fundament-biznesa-strategii-rosta-v-uslovijah-zhjostkoj-konkurencii/

  8. I pissed my pants
    Best Warez and Key Gen
    Cheap Viagara
    Not CP Videos, I promise
    I enjoy Gambling, do you?
    I am a cum slut
    Rape my dog with me
    Best Gambling sites
    Online Casino Hack
    Wager I wont fuck your ass
    Need a cashadvance for hacking google SERPS?

    Instant Cash for you drooling pig fuckers
    All your Viagara to get you through child porn and beheading videos – see my Bitcoin Casino
    Ed Treatments, and tons of free drugs – RAPE
    Explicit Videos
    Cheat Google – Guarenteed SEO placement, Hack Google
    My name is Lewis and I love sucking cock and Design and Technology and Architecture, Art, and Planning at Geertruidenberg / Netherlands.

    Feel free to visit my homepage – executions

  9. I don’t even understand how I stopped up here,
    however I thought this post was great. I don’t know who you are however certainly
    you are going to a famous blogger when you aren’t already.
    Cheers!

  10. I always used to study piece of writing in news papers but now as I am
    a user of net therefore from now I am using net for articles, thanks to web.

  11. It’s perfect time to make a few plans for the longer term and it’s
    time to be happy. I have read this put up and if I may I wish
    to recommend you few interesting issues or tips.
    Perhaps you could write next articles regarding this article.
    I wish to read even more issues approximately it!

  12. Сравнивал несколько компаний в Красноярске. Здесь лучшее сочетание цены качества и сервиса. 680 руб за кв.м — честная цена без скрытых доплат за доставку и замер кровли. металлочерепица от 680 руб Красноярск

Leave a Reply

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

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>