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.

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

  1. Доброго VSU Masherova carries out joint implementation of scientific and educational projects preparation of publications participation in conferences summer and winter schools internships language courses training of highly qualified specialists and teaching staff. Полная информация по ссылке – https://vsu.by/en/magistracy/english-language-masters-programmes.html видео витебск FEEDBACK VSU еЌљеЈ«з ”з©¶з”џиЇѕзЁ‹ Specialities Vitebsk university ABOUT VSU.by INSTITUTE FOR STAFF UPGRADING Vitebsk Удачи и успехов в учебе

  2. Experience professional-grade infrastructure engineered to maintain stability, speed, and operational reliability during periods of elevated trading activity.

  3. Hello just wanted to give you a quick heads up.

    The text in your post seem to be running off the screen in Opera.
    I’m not sure if this is a formatting issue or something to do with internet browser compatibility but
    I thought I’d post to let you know. The layout
    look great though! Hope you get the issue resolved soon. Thanks

  4. Для тех, кто ищет информацию по теме “Ежедневные новости и советы для фанатов бокса”, есть отличная статья.

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

    https://365boxing.ru

  5. Вывод из запоя в Сочи требуется когда человек не может самостоятельно прекратить употребление алкоголя испытывает похмелья признаки ломки тревогу бессонницу рвоту сильную слабость или резкое ухудшение самочувствие. Даже если запой длится несколько дней риск осложнений остается высокий: страдают системы организма печень сердце сосуды нервная система психика и общее состояние здоровья. Получить дополнительную информацию – http://vivod-iz-zapoya-sochi24.ru

  6. Hello, i think that i saw you visited my site thus i came
    to “return the favor”.I’m attempting to find things to enhance my web site!I suppose its ok to use
    some of your ideas!!

    my homepage … windsor horse racing results monday​ (Lula)

  7. Does your blog have a contact page? I’m having a tough time locating it but, I’d like to send you an email. I’ve got some suggestions for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it grow over time.

  8. Зацепил материал про Страница не найдена: как найти нужную информацию.

    Вот, можете почитать:

    https://07media.ru

  9. Особенно понравился раздел про Последние новости футбола мгновенно после матчей.

    Вот, делюсь ссылкой:

    https://livelokomotiv.ru

  10. Для тех, кто ищет информацию по теме “Страница не найдена: что делать дальше?”, там просто кладезь информации.

    Вот, можете почитать:

    https://komi11media.ru

  11. Вывод из запоя на дому подходит если пациент находится в сознании согласие получено а состояние не требует немедленной госпитализации. Врач нарколога приезжает по месту проживания соблюдает конфиденциальности работает аккуратно и помогает восстановить нормальное самочувствие после длительного употребления алкоголя. Подробнее можно узнать тут – вывод из запоя с выездом в казани

  12. Между прочим, если вас интересует Актуальные советы по финансовой грамотности в России, загляните сюда.

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

    https://rub-fin.ru

  13. Construir carreira em Sao Paulo nunca foi tao acessivel. No nosso site voce encontra as oportunidades de emprego no Brasil para todos os niveis de experiencia em SP e em todo o pais do jeito que faz sentido para a sua rotina.

  14. Кстати, если вас интересует Главные события и обновления в Смоленской области, посмотрите сюда.

    Вот, можете почитать:

    https://smol67media.ru

  15. What?s Taking place i am new to this, I stumbled upon this I have discovered It positively useful and it has helped me out loads. I am hoping to give a contribution & help other customers like its aided me. Great job.

  16. united statesn roulette online fast, no deposit bonus on sign up usa
    and top isle of man online casino license (Orval) pokies and casinos canadian league, or canadian casino guide slot payback info

  17. top online gambling sites uk, canadian poker admiral
    and new zealandn gambling habits, or free
    chips no deposit bonus united states

    Also visit my blog … blue chip casino brewfest 2022
    [Cruz]

  18. free spins shark freuky, best online pokies in united kingdom and new
    casino online usa 2021, or new zealandn online convergence
    between gambling and gaming, Valentina, pokies

  19. Нарколог на дом в Балашихе нужен когда человек после алкоголя запоя отравления абстинентного синдрома или употребления наркотиков не может самостоятельно восстановиться и нуждается в медицинской помощи. Вызов врача на дом позволяет быстро оценить состояние пациента провести осмотр подобрать препараты назначить лекарства поставить капельницу и определить возможно ли лечение в домашних условиях или требуется госпитализация в стационаре. Выяснить больше – http://narkolog-na-dom-balashiha13-4.ru

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>