将http://www.example.com重定向到http://example.com

时间:2014-09-17 17:21:14

标签: tomcat tomcat7 tuckey-urlrewrite-filter

如何在Tomcat中将http://www.example.com重定向到http://example.com?所有文档都侧重于Apache,但我正在托管一个Java应用程序。

3 个答案:

答案 0 :(得分:4)

的Apache

这应该是

的内容
# .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的

您可以在Tomcat中使用UrlRewriteFilter。像这样的规则应该适用于 /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>

不确定我是否写了错字,将其写在头顶

答案 1 :(得分:3)

在Tomcat8中 - 您有此选项 http://tomcat.apache.org/tomcat-8.0-doc/rewrite.html

如果您的网站是单个网络应用程序 - 请将其添加到ROOT.xml

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

然后将rewrite.config放入您的webapp的WEB-INF

看起来像这样:

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

这也可以在主机级别应用,因此它可以跨多个Web应用程序工作。

答案 2 :(得分:0)

我相信你是在当地环境中尝试这个。

打开“hosts”文件并添加ip条目。

例如:

127.0.0.1     www.example.com

“hosts”文件位于以下位置,具体取决于操作系统。

如果你在Windows中

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

如果你在Linux中

/etc/hosts

打开浏览器并立即尝试。它适用于(example.com或www.example.com)。 在托管环境中,这将在DNS级别上得到关注。所以不用担心。

注意:这将在您修改了主机文件的计算机上运行。