Reputation: 3602
How can I set Tomcat to automatically redirect to "www"? I want that if a user enters my domain like:
mydomain.com
he will be redirected to: www.mydomain.com
Upvotes: 6
Views: 2848
Reputation: 48807
Using Tuckey UrlRewriteFilter, you can also use the following rule:
<rule>
<condition type="header" name="host" operator="equal">^[^.]+[.][^.]+$</condition>
<from>^/.*</from>
<to qsappend="true" type="redirect" last="true">${replaceFirst:%{request-url}://://www.}</to>
</rule>
This one is quite interesting, since nothing is hardcoded: it works for any domain and keeps port number and protocol.
Functions seem to be implemented since v3.1.
There is a known issue with the qsappend
attribute: https://code.google.com/p/urlrewritefilter/issues/detail?id=116. You need to implement the fix specified on the link.
Simply create the package org.tuckey.web.filters.urlrewrite
in your webapp, create the class NormalRule
in it, and copy/paste the content of the following class: http://urlrewritefilter.googlecode.com/svn/trunk/src/main/java/org/tuckey/web/filters/urlrewrite/NormalRule.java.
Upvotes: 0
Reputation: 10220
wwwizer.com offers free naked domain redirect http://wwwizer.com/naked-domain-redirect
Point your naked domain like mysite.com to their IP, and they'll do a 301 redirect to www.mysite.com
Using a 301 redirect is the recommended way for SEO optimization.
Upvotes: 1
Reputation: 3602
The tuckey url rewrite filter can be used like this to do the proper redirection:
<rule>
<name>Canonical Hostnames</name>
<condition name="host" operator="notequal">^www.mydomain.com</condition>
<condition name="host" operator="notequal">^$</condition>
<from>^/(.*)</from>
<to type="redirect" last="true">http://www.mydomain.com/$1</to>
</rule>
Upvotes: 6
Reputation: 21720
If you are using Apache, simple do (on htaccess):
RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain.com
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301]
This way you make sure anything that is not using www starts using
UPDATE As you mentioned you don't have apache, I remembered I used this about a year ago. It does pretty much the same as mod_rewrite, and is fully supported by Tomcat. I used it with resin though, but I know it works the same way.
Greatest thing about it, is that it also runs on "mod_rewrite style", as you can see here. The only reason why I didn't continue using it, is because it will end up doing it at a server level, as opposed to a webserver level. Meaning it will call the JVM to interpret the redirect.
It works the same way though, and as mentioned before, can sue exactly the same thing you'd use on Apache.
Upvotes: 5