Redirecting http://www.example.com to http://example.com

荒凉一梦 提交于 2020-01-13 02:28:35

问题


How do I redirect http://www.example.com to http://example.com in Tomcat? All the documentation focuses on Apache, but I'm hosting a Java app.


回答1:


Apache

This should be something in the lines of

# .htaccess file contents
# Apache has the same docroot as the Java web app.
# Java webapp is running on port 8084
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# For sites running on a port other than 80
RewriteCond %{HTTP_HOST}   !^domain\.com [NC]
RewriteCond %{HTTP_HOST}   !^$
RewriteCond %{SERVER_PORT} !^80$
RewriteRule ^/(.*)         http://domain.com:%{SERVER_PORT}/$1 [L,R]

# And for a site running on port 80
RewriteCond %{HTTP_HOST}   !^domain\.com [NC]
RewriteCond %{HTTP_HOST}   !^$
RewriteRule ^/(.*)         http://domain.com/$1 [L,R]
</IfModule>

http://httpd.apache.org/docs/2.0/misc/rewriteguide.html

Tomcat

You can use UrlRewriteFilter in Tomcat. A rule like this should work for you in /WEB-INF/urlrewrite.xml:

<rule enabled="true">
    <name>Force HTTPS example</name>
    <note>Automatically redirects user requests.</note>
    <from>http://domain.com/(.*)$</from>
    <to type="permanent-redirect" last="true">http://www.domain.com/</to>
</rule>

Not sure if I made typo's, wrote this on top of head




回答2:


In Tomcat8 - you have this option http://tomcat.apache.org/tomcat-8.0-doc/rewrite.html

If your site is a single webapp - add this to ROOT.xml

  <Valve className="org.apache.catalina.valves.rewrite.RewriteValve"/>

Then put rewrite.config in your WEB-INF of your webapp

Which would look like this:

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

This can also be applied at the Host level too so it can work across multiple webapps.




回答3:


I believe you are trying this in the local environment.

Open the "hosts" file and add ip entry.

Eg:

127.0.0.1     www.example.com

"hosts" file is located in the following location depending on the OS.

If you are in Windows

C:\Windows\System32\drivers\etc\hosts

If you are in Linux

/etc/hosts

Open browser and try now. It will work for both (example.com or www.example.com). In Hosted environment, this would have been taken care at the DNS level. So no worries.

Note: This will work in the machines where you have modified hosts file.



来源:https://stackoverflow.com/questions/25896693/redirecting-http-www-example-com-to-http-example-com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!