Apache Tomcat 에서 RewriteValve 설정
1. 설정방법
1.1. server.xml
<Host> 아래에 다음의 내용을 추가한다.
<Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
1.2. conf/Catalina/%{SERVER_NAME}/rewrite.config
예를 들어 conf/Catalina/logiciel.kr/rewrite.config 이다.
1.2.1. http 를 https 요청으로 전환
RewriteCond %{HTTPS} off RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
예외는 다음과 같이 추가한다.
RewriteCond %{HTTPS} off RewriteCond %{REQUEST_URI} !^/(static-contents)/.* RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
그러면 http://%{SERVER_NAME}/static-contents/ 로 시작하는 요청은 https 로 전환하지 않는다.
1.2.2. 메인 페이지로 이동
RewriteCond %{REQUEST_URI} ^/$ RewriteRule ^.*$ https://%{SERVER_NAME}/graha/contents/list.html [L,R] RewriteCond %{REQUEST_URI} ^/index.jsp$ RewriteRule ^.*$ https://%{SERVER_NAME}/graha/contents/list.html [L,R] RewriteCond %{REQUEST_URI} ^/index.html$ RewriteRule ^.*$ https://%{SERVER_NAME}/graha/contents/list.html [L,R]
https://logiciel.kr/, https://logiciel.kr/index.html, https://logiciel.kr/index.jsp 요청은 https://logiciel.kr/graha/contents/list.html 으로 전환한다.
특정 IP(localhost 와 192.168.0.3) 를 제외하고 8080 포트로 들어오는 모든 요청을 https 로 redirect 시키는 설정은 다음과 같다.
RewriteCond %{REMOTE_ADDR} !127.0.0.1 RewriteCond %{REMOTE_ADDR} !0:0:0:0:0:0:0:1 RewriteCond %{REMOTE_ADDR} !192.168.0.3 RewriteCond %{SERVER_PORT} 8080 RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
그러면 8080 요청 중에서 다음과 같은 IP 에서 들어오는 요청은 제외한다.
- ipv4 의 loopback 주소인
127.0.0.0 - ipv6 의 loopback 주소인
0:0:0:0:0:0:0:1(설정파일에서는::1로 표기한다) 192.168.0.3
1.2.3. 추가적인 정보
Apache Tomcat 의 공식 문서는 다음과 같다.
https://tomcat.apache.org/tomcat-9.0-doc/rewrite.html
RewriteCond 에서 사용할 수 있는 Server-Variables 에 대한 정보는 소스코드에서 얻을 수 있다.
2. 관련주제
2.1. Apache HTTPD 설정
httpd.conf 에서 다음과 같은 부분의 주석을 제거한다.
LoadModule rewrite_module modules/mod_rewrite.so
httpd.conf 파일에서 http 요청 처리를 정의하는 VirtualHost 아래에 다음과 같은 내용을 추가한다.
RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
메인페이지로 이동은 다음과 같다.
RewriteRule ^/$ https://%{HTTP_HOST}%/graha/contents/list.html [L,R] RewriteRule ^/index.jsp$ https://%{HTTP_HOST}%/graha/contents/list.html [L,R] RewriteRule ^/index.html$ https://%{HTTP_HOST}%/graha/contents/list.html [L,R]
더 많은 정보는 다음과 같은 공식문서를 참조한다.
- https://httpd.apache.org/docs/current/rewrite/
- https://httpd.apache.org/docs/current/mod/mod_rewrite.html
- https://httpd.apache.org/docs/current/rewrite/flags.html
2.2. Let's Encrypt 인증서를 사용하는 경우
오래된 클라이언트까지 고려한다면, 자동으로 https 요청으로 전환하는 것은 신중하게 접근해야 한다.
사용자가 http 로 요청할 수 없다면, 사용자는 인증서 오류를 무시하는 것 외에 다른 선택을 할 수 없을 것이기 때문이다.
필자의 경우 인트라넷 서비스는 https 로 자동으로 전환하도록 설정하고, 인터넷 서비스는 로그인 페이지에 https 로 연결할 수 있는 링크와 안내문구을 추가하는 방법을 사용한다.