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

  1. I completely agree with the current property development trends in the
    region. Finding the right Interior design Malaysia partner is undoubtedly a top consideration 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 really helps in optimizing the
    budget. I’ve noticed that the Design and build
    interior design Malaysia model offered by Jolivin Interiors provides a
    highly efficient 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. Greatly appreciate this information;
    it adds a lot of value to my Residential interior design Malaysia research!

  2. At this time it appears like Drupal is the top blogging
    platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

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

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

  5. I think this is among the most vital information for me.
    And i’m glad reading your article. But wanna remark on some general things, The site
    style is great, the articles is really great : D. Good job, cheers

  6. Почему пользователи выбирают площадку KRAKEN?

    Маркетплейс KRAKEN заслужил доверие многочисленной аудитории благодаря сочетанию
    ключевых факторов. Во-первых,
    это широкий и разнообразный ассортимент, представленный сотнями продавцов.
    Во-вторых, интуитивно понятный интерфейс KRAKEN, который
    упрощает навигацию, поиск товаров
    и управление заказами даже для новых пользователей.
    В-третьих, продуманная система безопасных транзакций, включающая механизмы разрешения споров (диспутов) и возможность использования условного депонирования, что минимизирует риски для обеих сторон
    сделки. На KRAKEN функциональность
    сочетается с внимательным отношением к безопасности клиентов, что
    делает процесс покупок более предсказуемым,
    защищенным и, как следствие, популярным среди пользователей, ценящих анонимность и надежность.

  7. Hello every one, here every one is sharing such know-how, thus it’s good to read this web site, and I used to pay a visit
    this website every day.

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

    به شکل کلی

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

    بازی‌های کازینویی

    می‌گردن

    این مجموعه آنلاین

    می‌تونه مناسب باشه

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

    از طرف دیگه

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

    enfеjaronline جدید

    و

    سرویس sibbet

    محبوبیت دارن

    جمع‌بندی کلی

    خوب بود

    و

    در دفعات بعد

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

    .

    my ѕite :: راهنمای انتخاب سایت مناسب برای بازی انفجار, https://repairdetector.ir/,

  9. Excellent post. Keep writing such kind of information on your blog. Im really impressed by it. Hi there You have done a fantastic job. I will certainly digg it and in my opinion recommend to my friends. Im confident theyll be benefited from this website. tada gaming slots

  10. Hi its me I am also visiting this web page daily this web page is actually fastidious and the visitors are really sharing nice thoughts. tada gaming slots

  11. Wow fantastic weblog structure How long have you been blogging for? you made running a blog look easy. The overall glance of your site is magnificent as well as the content material tada gaming

  12. Hi there its pleasant article about media print we all be familiar with media is a great source of facts. tada-gaming.mobi

  13. Hey very nice blog Man .. Excellent .. Wonderful .. Ill bookmark your site and take the feeds additionally? I am satisfied to seek out a lot of useful info here within the submit we need develop more techniques on this regard thanks for sharing. . . . . . Gates of Olympus Xmas 1000

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>