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,014 thoughts on “How to switch to/from HTTPS using Apache as a proxy to Tomcat

  1. Доброго Надёжный HTTPS сертификат безопасность защищает данные пользователей и положительно влияет на ранжирование в поиске. Мы помогаем настроить корректное шифрование и перенести сайт на защищённый протокол без потерь. Поисковые алгоритмы отдают приоритет безопасным ресурсам и помечают их в выдаче. Ваши клиенты видят знак доверия в браузере и охотнее оставляют персональные данные. Внедряйте современные стандарты защиты и получайте преимущество в конкурентной борьбе. Эффективный парсинг выдач поисковых систем собирает ценные данные для стратегии продвижения и контент-плана. Мы автоматизируем сбор информации о позициях сниппетах и дополнительных элементах выдачи. Поисковые алгоритмы формируют сложные результаты и мы помогаем адаптироваться под их требования. Вы получаете структурированные данные для принятия решений и оптимизации каждого аспекта ресурса. Парсите выдачу профессионально и усиливайте точность маркетинговых действий. Больше информации по ссылке – https://7ooo.ru/allblogs/ обработка ошибок 404 страницы анализ конкурентов по ссылкам интеграция с агрегаторами отзывов юзабилити для удержания пользователей шеринг контента в соцсетях сквозная аналитика для бизнеса Удачи

  2. Обучение группы бухгалтеров новым возможностям 1С после обновления. За полдня разобрали все изменения ответили на вопросы. Работа пошла в новом режиме без потери темпа. 1С партнёр Белгород

  3. Между прочим, если вас интересует Страница не найдена: что делать дальше?, загляните сюда.

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

    https://20media.ru

  4. Работаем в общепите. Нужна была автоматизация калькуляции блюд и списания продуктов. Настроили техкарты теперь себестоимость считается автоматически. Сэкономили время бухгалтера в разы. 1С УНФ для строительства

  5. I completely agree with the current property development trends in the region. Finding the right
    Interior design Malaysia partner is undoubtedly a top priority for new homeowners today.
    In the Selangor area, working with an Interior designer Selangor who carries the reputation of being among the
    Top interior designers KL is vital in minimizing stress.
    I’ve noticed that the Design and build interior design Malaysia model offered by Jolivin Interiors
    provides a seamless solution, particularly when it comes to precision-engineered Custom kitchen cabinet Malaysia work.
    For those residing in the suburbs, Interior design Puchong is seeing massive
    growth, and the range of Interior design services Klang Valley is more impressive than ever.
    Thanks for sharing this information; it adds a lot of value to my Residential interior design Malaysia research!

  6. Склад запчастей в Алматы — нужная деталь нашлась сразу доставили за день. Теперь инвентаризация занимает часы вместо дней. Точность учёта выросла простоев из-за запчастей нет. ремонт спецтехники Алматы

  7. سلام، بنده دیروز به صورت کاملا تصادفی در
    اینترنت با این وبسایت برخوردم و واقعا تحت تاثیر قرار گرفتم.

    اطلاعاتش به‌دردبخور بود و خیلی کم پیش میاد همچین منبعی ببینم.
    احساس می‌کنم برای کاربرای زیادی مفید باشه.

    اگه دنبال محتوای مفید هستن پیشنهاد می‌کنم
    حتما سر بزنن. به طور کلی راضی‌کننده بود و قطعا
    باز هم سر می‌زنم

    به شکل خلاصه

    برای اونایی که می‌خوان وارد
    بشن

    پلتفرم‌های شرطی

    قصد فعالیت دارن

    این پلتفرم

    مطمئناً می‌تونه

    انتخاب درستی باشه

    همچنین

    سرویس‌هایی مثل

    enfejaronline قوی

    و

    siƄbet اصلی

    در حال رشد هستن

    نتیجه نهایی اینکه

    خیلی خوب بود

    و

    حتما

    برمیگردم بهش

    .

    Also visit my web site – مرجع رسمی

  8. Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех Ознакомиться с деталями – https://vivod-iz-zapoya-2.ru/

  9. Здравствуйте Строительство домов с бассейном — это роскошь которая становится доступной. Мы занимаемся строительством домов с бассейном чтобы вы могли наслаждаться плаванием в любое время года. Строительство домов с бассейном — это комфорт и роскошь. Строительство домов с бассейном — это ваш личный уголок для отдыха. Строительство бань — это услуга которая позволяет вам построить баню на вашем участке с учетом всех ваших пожеланий. Мы предлагаем строительство бань под ключ включая проектирование возведение и отделку. Все работы выполняются профессионалами с использованием качественных материалов что гарантирует долговечность и комфорт вашей бани. Мы предлагаем различные варианты бань чтобы вы могли выбрать наиболее подходящий для себя. Строительство бань — это уют и комфорт на вашем участке. Больше информации по ссылке – https://noziitopory.ru/remont/v-chem-otlichie-dekinga-i-terrasnoj-doski-keywords-otlichie.html готовые квартиры с отделкой от застройщика в москве строительства домов видео куплю квартиру в видном с отделкой внутренняя отделка деревянного дома строительство каркасной бани поэтапное строительство фото отделки домов фасады Удачи

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>