Report this

What is the reason for this report?

Tomcat rewrite url to redirect IP to domain name

Posted on April 2, 2020

Hi Team,

I’ve written a rewrite rue for my domain to redirect IP address to domain name. But the redirection is not working. I’m running Tomcat 9.0.19 on CentOS 7. I followed the answer mentioned in [https://www.digitalocean.com/community/questions/redirect-ip-to-domain-name] But that doesn’t seem to be working. Can you please let me know the right way to configure it?



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Heya,

I think you shouldn’t be trying to use such a redirect on the Application level. I think you look for this to be done on Apache.

Since you are using Tomcat, I’ll assume you are using Apache as a reverse proxy infront of it(let me know if that is not the case).

Create a Virtual Host for your domain: Create a new configuration file for your domain in the /etc/apache2/sites-available directory:

  1. sudo nano /etc/apache2/sites-available/your-domain.conf

Replace your-domain with your actual domain name.

Configure the Virtual Host: Add the following configuration to the newly created file, replacing your_domain.com and your_server_ip with your domain and server IP address, respectively:

<VirtualHost *:80>
    ServerName your_domain.com
    ServerAlias www.your_domain.com
    
    ProxyPreserveHost On
    ProxyPass / http://localhost:8080/
    ProxyPassReverse / http://localhost:8080/
</VirtualHost>

<VirtualHost *:80>
    ServerName your_server_ip

    RewriteEngine On
    RewriteRule ^(.*)$ http://your_domain.com$1 [R=301,L]
</VirtualHost>

In this configuration, the first VirtualHost block sets up a reverse proxy, forwarding requests to your domain to your Tomcat server running on localhost:8080. The second VirtualHost block redirects all requests made to the server IP to your domain.

Enable the Virtual Host: Enable the new Virtual Host configuration and restart Apache:

  1. sudo a2ensite your-domain.conf
  2. sudo systemctl restart apache2

After completing these steps, all requests made to your server IP should be redirected to your domain name. Additionally, your Apache server will act as a reverse proxy, forwarding requests to your domain to your Tomcat server running on localhost:8080.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.