Steps to Configure SSL on Tomcat and Setup Auto Redirect from HTTP to HTTPS

Filed Under: Java EE
Ssl Tomcat

Secured Socket Layer (SSL) is the cryptography protocol to provide message security over the Internet. It works on the notion of Private and Public keys and messages are encrypted before sending it over the network.

To configure SSL on Tomcat, we need a digital certificate that can be created using Java keytool for the development environment. For the production environment, you should get the digital certificate from SSL certificate providers, for example, Verisign, Entrust, Lets’ Encrypt.

Creating SSL Certificate

Follow the below steps to create your own digital certificate:


$ keytool -genkey -alias tomcat -keyalg RSA -keystore mycertificate.cert
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  Pankaj Kumar
What is the name of your organizational unit?
  [Unknown]:  Dev
What is the name of your organization?
  [Unknown]:  JournalDev
What is the name of your City or Locality?
  [Unknown]:  Bangalore
What is the name of your State or Province?
  [Unknown]:  Karnataka
What is the two-letter country code for this unit?
  [Unknown]:  IN
Is CN=Pankaj Kumar, OU=Dev, O=JournalDev, L=Bangalore, ST=Karnataka, C=IN correct?
  [no]:  Yes

Enter key password for <tomcat>
	(RETURN if same as keystore password):
Re-enter new password:
$ ls
mycertificate.cert

I have used the password “changeit” for keystore and key but you can use whatever you want.

Now our digital certificate is ready and the next step is to enable HTTPS communication port in Tomcat and set it to use our digital certificate for providing SSL support.

Tomcat HTTPS

To enable SSL open ~Tomcat_Installation/conf/server.xml file and uncomment following line:


<Connector port="8443" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" disableUploadTimeout="true"
               acceptCount="100" scheme="https" secure="true"
               keystoreFile="/Users/Pankaj/tomcat/conf/mycertificate.cert"
	       clientAuth="false" sslProtocol="TLS" />

To avoid any misplacement of the certificate, I have put that in the tomcat conf directory. Now restart Tomcat and try to access any web application over https with port 8443.

Tomcat SSL Enabled

Tomcat Redirect HTTP to HTTPS

So we can access any web application on both HTTP and HTTPS ports. We can set up tomcat to redirect all HTTP request to HTTPS port with some configurations.

  1. In ~TomcatInstallation/conf/server.xml

    For HTTP Connector, set the redirect port to the HTTPS connector port. It will look somewhat like this:

    
    <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
        <Connector port="8090" maxHttpHeaderSize="8192"
                   maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
                   enableLookups="false" redirectPort="8443" acceptCount="100"
                   connectionTimeout="20000" disableUploadTimeout="true" />
    </pre>
    </li>
    <li>In ~TomcatInstallation/conf/web.xml
    
    Add below configuration but make sure to add it after all the servlet-mapping tags.
    
    <pre>
    <!-- added by Pankaj for automatic redirect from HTTP to HTTPS -->
    <security-constraint>
    <web-resource-collection>
    <web-resource-name>Entire Application</web-resource-name>
    <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
    <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
    </security-constraint>
    

Restart the tomcat now and all the HTTP requests will automatically be redirected to HTTPS i.e http://localhost:8080/axis2 will be automatically redirected to https://localhost:8443/axis2

Note: If you don’t want to provide ports in the URLs, then use 80 for HTTP and 443 for HTTPS and in this case, you can skip the first step to automatic redirect HTTP requests to HTTPS because it will automatically pick the default port 443.

Update: If you are working on Tomcat, you might be interested in the following posts.

Comments

  1. Patrick says:

    One thing that might mess you up is setting up port 443 because any use of ports under 1024 require root access and most IT shops won’t let developers have root access on anything. So in this case, you might need apache web server to listen in on port 443 and redirect requests to port 8443 and just have the tomcat connector listen on 8443. Again, that may require admin intervention to edit the config files under apache web server. Good luck!

    PS: That issue is my #1 problem facing me – access to resources even on development servers. Maybe you all have looser restrictions or are just trying to get things to work locally. Just keep in mind as you go up the chain of deployment, local – dev – test -stage – prod, you might have to rethink how things work.

  2. Rama Krishna says:

    Hello Pankaj,

    I have followed the steps and I have deployed Jenkins in tomcat. somehow http://host:port/jenkins is not redirecting to https://host:port/jenkins by automatically but it is redirecting without Jenkins pattern (I mean http://host:port to https://host:port).
    Do you have any idea?

  3. Saket Yadav says:

    Hello Pankaj,

    Can you suggest how to configure tomcat 8080 redirect to SSL port based on Different Application on single Tomcat Service?

    For example :

    http://site1:8080/Application1 redirect to https://site1:443/Application1

    http://site2:8080/Application2 redirect to https://site2:445/Application2

    Both application on Tomcat 6.0.

  4. Sai says:

    Hi Pankaj, I have tomcat webservice running in Windows server and goes to http 301 status at least once in week. Restart of service not helping. Once I reboot entire server then it works again. Any idea whether it’s due to this redirect?

  5. Nirav Prajapati says:

    I have installed SSL Certificate successfully and i have also make relevant changes in server.xml and web.xml in tomcat/conf/ folder.

    In Production server request is redirect to https://localhost:8080/ but in live mean from internet it’s redirect to http://www.example.com Only.

    Please help me.

    1. Craig Cervo says:

      Important to remember that if you use keytool and a self signed certificate, when you attempt to access any web resource using https your browser will complain that the certificate is invalid and access is unsafe. In most cases you can choose to proceed and the access will be encrypted. In some ultra conservative browsers you may have to twiddle with settings to allow acces.

    2. Mragendra Rathore says:

      domain name config in nginx and apache

      proxy_pass http://127.0.0.1:8080;

  6. kiruba says:

    How can I manage post action while http to https? For example, I try to access http with post parameters, will it retrain after it is redirected to https. I guess on redirection it performs get action and no parameters aren’t migrated.

  7. Anil says:

    Good one , worked in first attempt.

  8. Mani says:

    I have add connector port 8443 for secure connection for my application. But my application becomes slow and suddenly stop working after some days. What could be the issue? Any idea?

  9. Sudeep Singh says:

    how to remove port number and application name of a java project from url bar instead of that i want like www.xyz.com only ?

    1. Nirav says:

      server.xml in your tomcat should use port 80
      and deploy your application as ROOT in webapps

  10. vatsal says:

    Awesome post. Got the right way in first try.

  11. Rajesh Lohani says:

    For tomcat 8.0.33 I ma getting issue while accessing the localhost through HTTPS :

    URL : https://localhost:8443/index.jsp

    05-Apr-2017 17:35:08.452 INFO [http-apr-8443-exec-7] org.apache.coyote.http11.AbstractHttp11Processor.process Error parsing HTTP request header
    Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
    java.lang.IllegalArgumentException: Invalid character (CR or LF) found in method name
    at org.apache.coyote.http11.InternalAprInputBuffer.parseRequestLine(InternalAprInputBuffer.java:181)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2500)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

  12. Muhammad Shahzad says:

    is it possible that port number remains the same and only it redirects to https?

  13. Harshal Deolekar says:

    Hello Pankaj,

    Regarding the certificate which we created, do we need to give it to the client?

    Let say my client is actually a web service client which is calling my web services. I need to authenticate my clients web serivce call by using certificates? In that case, should I ask my clients to install this certificate on their production server?

    If possible, post an article on why and how certificates used.

  14. UnitedMarsupials says:

    The article mentions modifications to two files — server.xml and web.xml — without explicitly stating, whether BOTH steps need to be taken, or if EITHER one is sufficient. Please, clarify. Thank you!

  15. Bhavya Narula says:

    Hi Pankaj,

    Thanks for the concise article,
    I am using openshift cloud to host my tomcat application, I did the above given steps and the http->https redirection did take place. But somehow it adds the port number to URL:
    http://xyz.com —-> https://xyz.com:8443

    I don’t want the port number in the URL as this fails to validate my SSL certificate.
    Please let me know if you have any insight on this

    Thanks

  16. Satyam Singh says:

    Can anyone help me out in configuring redirect from 8080 to 8443 in tomcat…?

    Actually, whenever i am hitting my domain it is redirecting into 8443 port with it is changing its domain value like;
    i have put: www.abcd.com. it is redirecting to https://127.0.0.1:8443/ProjectName

    but i am just redirecting port number, then why it is mapping my domain name to localhost IP.

    C-an anyone give me idea about this

    here is my server.xml mapping below…

    1. Pankaj says:

      Please put the XML or HTML code in pre tag, otherwise it will be eaten up as HTML tag.

  17. Satyam Singh says:

    I have tried so many options but this is thw simplest one…

    Still one question :
    Suppose, my Web application os hosted on tomcat 8080 port but my domain is mapped with Apache server and listening 80 port.
    I am redirecting request from 80 Apache to 8080 tomcat, where my application hosted.
    So, in this case where to install SSL CERTIFICATE…?
    In Tomcat or In Apache…?

    I m getting stuck, if possible look into this

    Thanks

  18. Vinayak Ghorpade says:

    It was really very helpful
    Thank You:-)

  19. Vinayak Ghorpade says:

    Thank you it was very helpful

    1. Santosh kumar Jaiswal says:

      Hi,

      But in my case, whenever i enter url like this (http://localhost:8443) it will not redirect to https://localhost:8443.

      Please do the needful

      1. Sadik Tamboli says:

        having same question. waiting for reply.

  20. Vimalan Ravindran says:

    Hi Pankaj I have one question, I have enabled BASIC authentication for my application by putting required entries for it in its respective web.xml file, also I have enabled port redirection from 8080 to 443 in the web.xml file of tomcat. After enabling port redirection while accessing my application authentication is not getting prompted, can you please advise me why is the strange behaviour happening

  21. Pratham says:

    Hi Pankaj,
    The redirection works only at the root ex:if i give my application as http://my_server_ip it will redirect to https://my_server_ip but when i try to give the url as http://my_server_ip/application It won’t redirect to https://my_server_ip/application. Could you please suggest a workaround for this.

    Thanks for this awesome post.

  22. Aqueel Alam says:

    Hi:
    i want to host my side from my computer.
    i have a router with static IP .
    my apache tomcat port if 8080;

    how my jsp side host please help me.

  23. Hardik says:

    I have successfully setup the SSL arrangement as described in the article. However, the redirect from http to https is a 302 redirect i.e., temporary redirect. How can I make this redirect a permanent one i.e., 301 redirect?

  24. Labanya Kumar says:

    I made similar configuration changes in my tomcat server.xml as explained in the tutorial and have placed myCertificate.cert in conf directory. but while i am trying to access application using http url, browser gets redirected to https with 8443 port but home page mentioned in the browser URL.is not displyed. getting ERR_connection_refused

  25. ravikiran says:

    can u let me know the steps how to hide port number from url?

  26. Shashank says:

    Sorry please delete this comment , I got it , Just wondering is it necessary to have index.jsp or .html file in webapps/myapp folder , when i tried using http://localhost:8080/myapp it won’t work but when i specified .html file and accessed in same it worked ?

    Also it will be great if you can confirm below two points
    1. Is it necessary to have web.xml
    2. Does accessing the servlet way has changed now

    sometime it work as
    http://localhost:8080/myapp/servlet/MyServlet
    and some where http://localhost:8080/myapp/MyServlet , why is it so or am i missing something ?

    Thanks

    1. Pankaj says:

      It’s not required to have index.html in webapp root folder, you can define any file as welcome-file in web.xml and it will be returned when you will hit your application root.

      It’s not required to have web.xml in webapp, but it’s best practice to have it even if you are using annotations only for configuring servlets.

  27. Tapan says:

    Great….thanks…

  28. Mars says:

    Hi,buddy
    I am a java programmer and also a blogger.would u give me a favor?I’m interested in your blog theme.Could you send a email to me with the theme.thank you! mars.ma.cn@gmail.com

  29. Sathish says:

    Nice post.. Thanks for this information….

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages