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

  1. در یک نگاه کلی

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

    سایت‌های شرطی

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

    این پلتفرم

    به نظر گزینه باشه

    ارزش امتحان داشته باشه

    یه نکته مهم اینه که

    برندهای شناخته‌شده‌ای مثل

    دامنه enfejaronlіne

    و

    sibbet رسمی

    پیشرفت قابل توجهی داشتن

    جمع‌بندی کلی

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

    و

    در آینده نزدیک

    استفاده خواهم کرد

    My web site سایت علمی پژوهشی (Jovita)

  2. It’s hard to find well-informed people about this
    topic, but you seem like you know what you’re talking about!
    Thanks

  3. Thanks for ones marvelous posting! I certainly enjoyed reading it, you may be a great author.I will be sure to
    bookmark your blog and may come back sometime soon. I want to encourage you continue your great posts, have a
    nice afternoon!

  4. سلام، خودم امروز در حال جستجو
    تو اینترنت با این وبسایت پیداش کردم و بدون
    اغراق نظرم روجلب کرد. نوشته‌هاش جذاب بود و به ندرت همچین سایتی
    پیدا کنم. به نظرم برای افراد مختلف
    کاربردی باشه. برای کسایی که دنبال محتوای مفید هستن پیشنهاد می‌کنم حتما برن ببینن.
    در کل تجربه خوبی بود و احتمالا باز هم سر می‌زنم

    در پایان کار

    برای علاقه‌مندان به

    سرگرمی‌های پولی

    سرگرم میشن

    این وبسایت

    کاملا میتونه

    گزینه ارزشمندی باشه

    از سوی دیگر

    برندهای شناخته‌شده‌ای مثل

    enfeјarߋnline فعال

    و

    sibbet اصلی

    کاربرای زیادی دارن

    در آخر کار

    جذاب بود

    و

    بدون شک

    سر میزنم دوباره

    .

    Here is my web blog … سایت فناوری

  5. Aw, this was a really nice post. Finding the time and actual effort to make a
    very good article… but what can I say… I procrastinate a lot and don’t seem to get anything done.

  6. you’re really a good webmaster. The web site loading speed is incredible.
    It kind of feels that you’re doing any unique trick. Furthermore,
    The contents are masterpiece. you’ve performed a
    magnificent activity on this subject!

  7. Hello everyone Upgrade your equipment with our efficient wow gear boost service for better performance. Expand your wealth in game with our reliable service where wow gold for sale is always available. We source gold through legitimate methods to ensure your account remains safe from bans. Instant delivery options mean you can get your currency immediately after purchasing online. Competitive rates make it affordable to buy large amounts of gold for your trading needs. Support your crafting and auction house ambitions with a steady supply of in game currency. The most complete information on the website – https://www.wow-power-leveling.org/Gameplay/wow-two-person-flying-mounts fast wow leveling boost wow boosting wow profession boost cheapest wow gold wow level boost dragonflight gold Good luck and good gameplay

  8. Для тех, кто ищет информацию по теме “Актуальные события Воронежа: интервью и проекты”, там просто кладезь информации.

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

    https://media36.ru

  9. Good day This post could not be written any better Reading through this post reminds me of my old room mate He always kept chatting about this. I will forward this write-up to him. Fairly certain he will have a good read. Thank you for sharing 在线购买他达拉非片用于肛交XXX色情

  10. Привет всем Как построить дом быстро и без лишних расходов Строительство домов под ключ — это не просто возведение стен а создание комфортного пространства для жизни. Мы реализуем проекты любой сложности: от компактных коттеджей до просторных домов для всей семьи. Современные технологии качественные материалы и контроль на каждом этапе. Полная информация по ссылке – https://dagtechstroy.ru/what-we-do/ новости о строительстве строительство ленточного фундамента стройконтроль в строительстве проектирование дома стоимость Политика конфиденциальности – ДагТехСтрой – строительство капитель это в строительстве Удачи и комфорта в жизни Почему качественный проект дома экономит деньги 57b7713

  11. Appreciating the hard work you put into your website and detailed information you present.
    It’s good to come across a blog every once in a while that isn’t the
    same out of date rehashed material. Great read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  12. Wonderful items from you, man. I have remember your stuff prior to and you’re simply extremely
    wonderful. I really like what you have bought right
    here, certainly like what you are stating and the way in which by which you
    say it. You’re making it entertaining and you still
    care for to keep it wise. I can’t wait to read much more from
    you. This is really a terrific website.

  13. Добрый день 24/7 аварийный сервис — когда поломка не ждет Каждая поломка — это РЅРµ только проблемы СЃ оборудованием РЅРѕ Рё возможные убытки для бизнеса. Наши специалисты готовы быстро отреагировать РЅР° любые неисправности Рё устранить РёС… чтобы избежать простоя. РњС‹ предлагаем комплексные решения для вашего оборудования обеспечивая РЅРµ только быстрый ремонт РЅРѕ Рё повышение его производительности. РњС‹ понимаем как важна каждая деталь Рё наши решения РїРѕРјРѕРіСѓС‚ минимизировать затраты Рё продлить СЃСЂРѕРє службы вашей техники. Полная информация по ссылке – https://dag-techservice.ru/services/electrical.html наладка технологического оборудования РєРЅРёРіР° автоматизация упаковочного цеха монтаж промышленной теплоизоляция оборудования промышленная печь наладка FAQ — DAG TechService бригады монтажа промышленного оборудования Удачи и комфорта в жизни Достижения которых мы гордимся — кейсы успешных проектов 35ffc69

  14. I’m really loving the theme/design of your web site. Do you ever
    run into any browser compatibility problems? A small number
    of my blog readers have complained about my blog not operating correctly in Explorer but
    looks great in Firefox. Do you have any advice to
    help fix this problem?

  15. I got this web site from my friend who informed me
    regarding this site and now this time I am browsing this site and reading very informative content at this place.

  16. Хочу выделить раздел про Качественная футбольная журналистика и аналитика.

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

    https://sportcska.ru

  17. great post, very informative. I ponder why the other experts of this
    sector do not realize this. You must continue your writing.
    I am sure, you’ve a great readers’ base already!

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>