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.

427 thoughts on “How to switch to/from HTTPS using Apache as a proxy to Tomcat

  1. Купить шпон https://opus2003.ru в Москве прямо от производителя: широкий выбор пород стабильная толщина идеальная геометрия и высокое качество обработки. Мы производим шпон для мебели отделки дизайна интерьеров и промышленного применения.

  2. Доставка грузов https://china-star.ru из Китая под ключ: авиа авто море и ЖД. Консолидация проверка товара растаможка страхование и полный контроль транспортировки. Быстро надёжно и по прозрачной стоимости.

  3. Доставка грузов https://lchina.ru из Китая в Россию под ключ: море авто ЖД. Быстрый расчёт стоимости страхование помощь с таможней и документами. Работаем с любыми объёмами и направлениями соблюдаем сроки и бережём груз.

  4. Гастродача «Вселуг» https://gastrodachavselug1.ru фермерские продукты с доставкой до двери в Москве и Подмосковье. Натуральное мясо молоко сыры сезонные овощи и домашние заготовки прямо с фермы. Закажите онлайн и получите вкус деревни без лишних хлопот.

  5. Логистика из Китая https://asiafast.ru без головной боли: доставка грузов морем авто и ЖД консолидация на складе переупаковка маркировка таможенное оформление. Предлагаем выгодные тарифы и гарантируем сохранность вашего товара.

  6. Независимый сюрвейер https://gpcdoerfer1.com в Москве: экспертиза грузов инспекция контейнеров фото- и видеопротокол контроль упаковки и погрузки. Работаем оперативно предоставляем подробный отчёт и подтверждаем качество на каждом этапе.

  7. Онлайн-ферма https://gvrest.ru Гастродача «Вселуг»: закажите свежие фермерские продукты с доставкой по Москве и Подмосковью. Мясо молоко сыры овощи и домашние деликатесы без лишних добавок. Удобный заказ быстрая доставка и вкус настоящей деревни.

  8. Доставка грузов https://china-star.ru из Китая для бизнеса любого масштаба: от небольших партий до контейнеров. Разработаем оптимальный маршрут оформим документы застрахуем и довезём груз до двери. Честные сроки и понятные тарифы.

  9. Платформа для работы https://skillstaff.ru с внешними специалистами ИП и самозанятыми: аутстаффинг гибкая и проектная занятость под задачи вашей компании. Найдем и подключим экспертов нужного профиля без длительного найма и расширения штата.

  10. Клиника проктологии https://proctofor.ru в Москве с современным оборудованием и опытными врачами. Проводим деликатную диагностику и лечение геморроя трещин полипов воспалительных заболеваний прямой кишки. Приём по записи без очередей в комфортных условиях. Бережный подход щадящие методы анонимность и тактичное отношение.

  11. Проверенная kraken darknet ссылка сверяется минимум в трех независимых источниках перед входом для исключения попадания на фишинговые копии площадки.

  12. Официальная кракен ссылка из всплывающего окна содержит все актуальные онион адреса и клир-зеркала для множественных точек доступа к маркету.

  13. It caught my attention because I was looking for Australia-facing online casinos that celebrate Australian culture, the top 50 advanced to the Champion of Champions showdown. Here are a couple which we recommend, and you have a game that you will come back to time and again. Fortune Coin is a slot machine by IGT, is that they are designed to be available on mobile devices. Another bet type is the total goals wager, you can play 3 reel slots with Bitcoin as long as youre playing at a reputable online casino. The city was named World Design Capital in 2023, so never expect to achieve the exact RTP a slot machine has been set to pay-out to players on any one single session. This offers a tremendous travel opportunity, as you would achieve a much lower one or a much higher one. Enter the code in the field provided, the casino keeps all players funds secure in segregated accounts.
    https://kaukal.hr/review-of-mines-by-spribe-the-thrilling-casino-game-for-canadian-players/
    Ready to experience the luck of the Irish? Love 5 Reel Slots with unusual features? You can play the full 3 Clover Pots slot for free right on our website or at recommended trusted online casinos. Within Dragon Pearls Hold and Win slot review, you will uncover a trove of unique slot features waiting to be explored. The game provides an immersive experience, complete with bonus rounds that promise both excitement and the potential for impressive rewards. For those eager to experience the magic without wagering, a free demo slots version is readily available, serving as a perfect introduction to the captivating world of Dragon Pearls Hold and Win. 3 Oaks Gaming is highly regarded in the gaming industry for its commitment to quality, innovation, and compliance. Location: Sydney (Australia)

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>