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

  1. What i don’t understood is in reality how you’re no longer really much
    more well-preferred than you might be now. You are so intelligent.
    You understand therefore considerably when it comes to this subject, produced me individually
    consider it from numerous various angles. Its like men and women aren’t fascinated unless it’s one thing to do with Girl gaga!
    Your individual stuffs excellent. At all times deal with
    it up!

  2. درود، من مدتی قبل هنگام گشتن تو
    اینترنت به این سایت آشنا شدم و صادقانه برام جالب بود.
    مطالبش کاربردی بود و کمتر همچین سایتی پیدا کنم.
    احساس می‌کنم برای کاربرای زیادی
    ارزش دیدن داره. برای کسایی
    که دنبال یه سایت خوب هستن پیشنهاد می‌کنم حتما برن ببینن.
    در مجموع تجربه خوبی بود و احتمالا دوباره استفاده می‌کنم

    در پایان کار

    برای کسانی که

    کازینو اینترنتی

    در این حوزه فعالیت دارن

    این سرویس آنلاین

    به نظر میاد بتونه

    کمک‌کننده باشه

    در ضمن

    اسم‌هایی مثل

    enfejaronline جدید

    و

    sibЬet حرفه‌ای

    تونستن کاربرا جذب کنن

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

    قابل قبول بود

    و

    به زودی

    باز هم سر می‌زنم

    .

    Feel free to visit my site وب سایت دانشگاهی

  3. Если вы любите сериалы то этот пост для вас нашла интересное место Смотреть кино онлайн не выходя из дома – это не только удобно но и безопасно. Вам не нужно беспокоиться о парковке билетах и толпе людей. мелодрамы Просто устраивайтесь поудобнее и наслаждайтесь просмотром. Сделайте свой вечер идеальным. Больше информации по ссылке: — http://www.filmy-serialy-online-1.top драмы онлайн без регистрациикинотеатр онлайн бесплатно hdсмотреть фильмы онлайн hd 1080 Смотрите и делитесь впечатлениями

  4. Привет всем Строительство домов с летней кухней — это удобное решение для тех кто любит готовить на свежем воздухе. Мы предлагаем строительство домов с летней кухней чтобы вы могли наслаждаться временем на улице. Строительство домов с летней кухней — это идеальное решение для дачи. Строительство домов с летней кухней — это комфорт на природе. Квартира на ремонт — это шанс преобразить ваше жилье и сделать его более удобным и функциональным. Мы предлагаем услуги по ремонту квартиры где каждый проект индивидуален. Все работы выполняются с учетом ваших пожеланий и мы используем только качественные материалы. Квартира на ремонт — это шанс создать дом своей мечты. Квартира на ремонт — это шаг к улучшению вашего жилья. Больше информации по ссылке – https://furnipro.info/news/primernaja_stoimost_remonta_nebolshoj_kvartiry/2019-09-21-54 ремонт полов доме дом все для ремонта фото домов отделки организации по ремонту домов ремонт в домах в выходные дни ремонт дом 24 Удачи

  5. Доброго Новые технологии для нового уровня вашего бизнеса Что если Р±С‹ РІС‹ могли избежать поломок еще РґРѕ РёС… возникновения? РЎ нами это РІРѕР·РјРѕР¶РЅРѕ. РњС‹ предлагаем РЅРµ только диагностику РЅРѕ Рё профилактику которая предотвращает потенциальные проблемы СЃ оборудованием. Благодаря нашему РїРѕРґС…РѕРґСѓ РІС‹ будете уверены что ваше оборудование будет работать без задержек Рё СЃ максимальной производительностью. Полная информация по ссылке – https://dag-techservice.ru/services/ монтаж промышленного оборудования описание котельное оборудование автоматика определение сервисное обслуживание оборудования модернизация электропривода Формовочное устройство DN 600 РїСѓСЃРєРѕ наладка технологического оборудования Удачи и комфорта в жизни Ремонт который возвращает оборудование к жизни f1635ff

  6. I am not sure where you are getting your information, but great topic.
    I needs to spend some time learning much more or understanding more.
    Thanks for wonderful information I was looking for this information for my mission.

  7. My spouse and I stumbled over here different web page and thought
    I might check things out. I like what I see so now i’m
    following you. Look forward to looking at your web page repeatedly.

  8. Здравствуйте Строительство домов с панорамными окнами Строительство домов из современных материалов позволяет создать надежное и теплое жилье. Мы подбираем оптимальные технологии для каждого проекта чтобы дом был долговечным комфортным и экономичным в эксплуатации. Полная информация по ссылке – https://dagtechstroy.ru/architectural-design/ строительство всм строительство домов из блоков стоимость ов в строительстве расшифровка строительство домов из газобетона услуги Урбанистический Проект «Современный Город Спектро» – ДагТехСтрой – строительство майнкрафт моды на строительство Удачи и комфорта в жизни Кровля дома: какие материалы служат дольше bd1082_

  9. Hi it’s me, I am also visiting this website on a regular basis, this web page is in fact good and the viewers are
    really sharing fastidious thoughts.

  10. Very soon this web site will be famous among all blogging
    and site-building users, due to it’s pleasant articles

  11. I don’t know if it’s just me or if perhaps everybody
    else experiencing issues with your site. It looks like some of the written text in your posts are running off the screen. Can someone else please comment
    and let me know if this is happening to them as well?
    This may be a problem with my browser because I’ve had this
    happen previously. Appreciate it

  12. I’m curious to find out what blog platform you happen to
    be working with? I’m experiencing some minor security issues
    with my latest website and I’d like to find something more risk-free.
    Do you have any recommendations?

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

    در دید کلی

    برای افرادی که

    پیش‌بینی مسابقات

    میخوان تست کنن

    این آدرس

    کاملا میتونه

    قابل توجه باشه

    از سوی دیگر

    وبسایت‌هایی مثل

    enfejаronline اصلی

    و

    sibbet

    حضور پررنگی دارن

    در جمع‌بندی

    رضایت‌بخش بود

    و

    قطعا

    بهش برمی‌گردم

    .

    Feel free to surf tto my webpаge … مجله پزشکی (9x45mr.walbrzych.pl)

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>