Tomcat – How to rewrite www to non www in tomcat server

rewritetomcat

I am running a tomcat server on a vps server which is having centos. My website is browsing with
mydomain.com and www.mydomain.com. But I don't want to see www in my url.
i.e. If I browse with www.mydomain.com, it should be redirected to mydomain.com.

For this thing, I have added Rewrite valve in my context.xml and also created rewrite.config file in
/opt/apache/conf/Catalina/mydomain.com and added below rewrite rules

RewriteCond %{HTTP_HOST} ^www.mydomain.com [NC]

RewriteRule ^(.*)$ mydomain.com/$1 [L,R=301]

But it is not working. When I browse with www.mydomain.com, the url stays the same. It is not redirecting
to mydomain.com

Please suggest me where I was doing wrong.

Best Answer

Firstly your rewrite rule has a small error. It should use a full URL for the redirect (cf. description of redirect flag):

RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com$1 [L,R=301]

However this doesn't explain why the rewrite rule is not triggered. As mentioned in the comment above, you must make sure that the rewrite.config file is in the write place. With the default server.xml configuration (engine name Catalina, host name localhost) you need to put it in:

  • $CATALINA_BASE/conf/Catalina/localhost if you added the RewriteValve to the <Host> element of your server.xml.
  • the WEB-INF folder of your application, if you added the RewriteValve to the <Context> element of your application.

In any case it might help you to increase the log level of the Servlet logger:

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = FINE

in $CATALINA_BASE/conf/logging.properties, which will log to localhost.<date>.log the lines:

Read configuration from: ...
Add rule with pattern ^(.*)$ and substitution http://example.com$1 
Add condition ^www.example.com test %{HTTP_HOST} to rule with pattern ^(.*)$ and substitution http://example.com$1 [NC] 

whenever the RewriteValve is properly configured.

Related Topic