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.

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

  1. 의심할 여지 없이 귀하가 언급한 것을 믿습니다.

    당신의 가장 좋아하는 이유는 인터넷에서
    가장 단순한 것로 염두에 두어야 할
    것처럼 보였습니다. 저는 당신에게 말합니다, 저는 사람들이 그들이
    단순히 모르는 이슈를 생각할 때 화가
    나 확실히 느낍니다. 당신은 부수적인 영향 없이
    모든 것을 깔끔하게 정의하고, 정상을 정확히 맞췄습니다.
    다른 이들이 신호를 받을 수 있습니다.

    확률이 높게 더 얻기 위해 다시 올 것입니다.

    감사합니다

    This paragraph will help the internet users for creating new weblog or even a weblog from start to end.

    I can’t get enough of your blog! Your posts are so well-researched, and I
    love the clarity in your writing. Have you
    considered guest posting on other sites to expand your reach?
    Keep up the outstanding work!

    이 블로그는 정말 놀라운 곳이에요!
    EdgeNRoots 관련 콘텐츠가 너무 유익해요. SEO를 강화하기 위해 키워드 최적화 팁이 있다면 공유해
    주세요. 멋진 포스트 감사합니다!
    감사합니다!

  2. Хороший обзорный материал по SEO. Автор разбирает, зачем нужно продвижение, какие задачи оно решает и почему без него бизнесу в онлайне сложно. Полезно для новичков: https://wisentbull.ru/seo-prodvizhenie-sajta-iskusstvo-i-nauka-uspeha-v-cifrovom-mire/

  3. В этой публикации мы предлагаем подробные объяснения по актуальным вопросам чтобы помочь читателям глубже понять их. Четкость и структурированность материала сделают его удобным для усвоения и применения в повседневной жизни. Подробнее тут – https://vivod-iz-zapoya-2.ru/

  4. Искал информацию именно про Яндекс и нашёл отличный гайд по накрутка пф яндекс. Автор объясняет специфику алгоритмов Яндекса и даёт стратегии, которые реально работают в 2026 году.

  5. A Gates of Olympus é jogada no formato de 6 rolos e 5 linhas, tendo volatilidade alta. As rodadas surgem de maneira fluida, com a particularidade dos símbolos vencedores serem eliminados, aparecendo outros que possibilitam novas combinações. A animação dramática e uma boa seleção de funcionalidades bónus criam um apelo instantâneo ao Gates of Olympus 1000. Alguns cassinos online, como Superbet, Novibet e VBet, oferecem a versão grátis do Gates of Olympus aos seus jogadores. Basta selecionar a opção de demonstração para jogar. Alguns cassinos online, como Superbet, Novibet e VBet, oferecem a versão grátis do Gates of Olympus aos seus jogadores. Basta selecionar a opção de demonstração para jogar. Este slot tem uma RTP de 96,50% e alta volatilidade. Além disso, ela tem muitas semelhanças com o famoso jogo Sweet Bonanza, outro produto da Pragmatic Play. Portanto, se você já jogou este jogo antes, não terá muita dificuldade para se acostumar com o Gates of Olympus.
    https://thinkwhitematter.com/play-leon-casino-revisao-do-jogo-no-casino-online-para-portugal/
    Conecte-se conosco Antes de colocar seu dinheiro nas rodadas desse grid 6×5, conheça as funcionalidades na versão gratuita. Conheça todos os detalhes e estabeleça rígidos limites para sua banca. Dessa forma, sua experiência será ainda mais cheia de emoção. Para se aprofundar no funcionamento do jogo, confira o guia completo de Como jogar Gates of Olympus. Gates of Olympus é um excelente título da  Pragmatic Play que leva os jogadores numa jornada até o Olimpo. Ao contrário de outros temas do mesmo provedor, como no caso das slots Sweet Bonanza e Sugar Rush, este jogo oferece uma experiência mais intensa devido à sua elevada volatilidade, sendo uma escolha popular em casinos online em Portugal. O slot Gates of Olympus foi projetado de forma ideal para todos os dispositivos, como PC, telemóvel e tablet.

  6. Статья охватывает современные тренды SMM: короткое вертикальное видео, живые эфиры, использование AI-инструментов. Автор также разбирает, как правильно настраивать таргетинг и интегрировать соцсети с CRM. Актуально: https://iwatt24.ru/uslugi-smm/

  7. В этом интересном тексте собраны обширные сведения которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому Исследовать вопрос подробнее – https://vivod-iz-zapoya-2.ru/

  8. Дом из клееного бруса на берегу озера — проекты для Ленобласти

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>