Ubuntu環境、http接続をhttps接続に

Ubuntu環境、http接続をhttps接続に

Ubuntu環境、ApacheとTomcatでhttp接続をhttps接続に変換する。

関連ページ

X(旧Twitter)では、プロフィールに自分のサイトを打ち込んだ場合、何故か強制的にhttp表記に書き換えられるという謎の仕様があります。
仮にhttps://unity-engineer.topと打ち込んでも、http://unity-engineer.topに変換させられます。

今時のGoogleChromeではhttpのサイトに移動すると「危険なサイトです」みたいな警告が出るので、http接続は避けたいです。
この記事ではApacheとTomcatが連携されているのを前提とし、RewriteRuleを使ってhttp接続を強制的にhttps接続に変換していきます。

対象サイトのVirtualHostにRewriteRuleを追記

RewriteRuleはhttpd.conf(Ubuntuでは/etc/apache2/apache2.conf)に記すのが一般的らしいです。
ただ複数サイトを運営しているとVirtualHostに記載した方が便利で、UbuntuではVirtualHost専用のファイル群があります。
/etc/sites-available/ディレクトリにあるファイルがそれで、今回は/etc/sites-available/default-ssl.confをコメントアウトして書き換えてしまいます。
もし自分で作ったconfファイルを使いたい場合、下のコマンドを打ってApacheに認識させる。
a2ensite 
[confのpath]

viコマンドでファイを開き、ポート80(http接続)とポート443(https接続)のVirtualHost設定を行います。
下の設定では、ポート80接続した時にはApacheがTomcatには繋がずに、Apacheのポート443接続へそのまま受け流します。
LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so    
LoadModule proxy_http_module /usr/lib/apache2/modules/mod_proxy_http.so    
LoadModule ssl_module /usr/lib/apache2/modules/mod_ssl.so    

#強制的にhttps接続へ受け流す。
    
<VirtualHost *:80>    
    DocumentRoot /var/www/    
    ServerName unity-engineer.top    
    ErrorLog /var/log/apache2/unity-engineer.top.error.log    
    CustomLog /var/log/apache2/unity-engineer.top.access.log combined    

    RewriteEngine On    
    RewriteCond %{HTTPS} off    
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301]    
</VirtualHost>

#https接続でもhttp接続でもこちらを通る。
    
<VirtualHost *:443>    
    DocumentRoot /var/www/    
    ServerName unity-engineer.top    
    ErrorLog /var/log/apache2/unity-engineer.top.error.log    
    CustomLog /var/log/apache2/unity-engineer.top.access.log combined    

    SSLEngine on    
    SSLProtocol all -SSLv2    
    SSLCertificateFile      
[unity-engineer.top  cert.pem(SSLサーバー証明書)の path]
    
    SSLCertificateKeyFile   
[unity-engineer.top  privkey.pem(秘密鍵)の path]
    
    SSLCertificateChainFile 
[unity-engineer.top  chain.pem(中間証明書)の path]
    

    ProxyRequests Off    
    SSLProxyEngine On    
    ProxyPass / https://unity-engineer.top:
[Tomcatのhttpsポート設定]
/
[Tomcatのwebapps下サイトディレクトリ]
    
    ProxyPassReverse / https://unity-engineer.top:
[Tomcatのhttpsポート設定]
/
[Tomcatのwebapps下サイトディレクトリ]
    
</VirtualHost>    

一応RrewiteのModuleのコードからOnにしておきます。
a2enmod rewrite

再起動して完了です。
sudo service apache2 restart
これでXからhttpのサイトへ接続したとしても、内部的にhttps接続に切り替わります。
0
0