简体   繁体   中英

permanent 301 redirect in Tomcat 5.5

可以在Tomcat 5.5独立运行的情况下进行301重定向,而不是在IIS / Apache之后吗?

There isn't a way to set this up as easily as you're able to with Apache. The closest thing would be to make a servlet or jsp to handle the redirect and then map it to the URL you want to redirect from. In the servlet or jsp it would do something like:

response.setStatus(301);
response.setHeader("Location", "http://www.example.com/redirect-to-here.html" );

To redirect entire folder to new location you need both a JSP and configuration to call this jsp upon 404.

In index.jsp you need to modify your redirect behavior. Below code would redirect from OldApp folder to NewApp folder on the same server.

index.jsp:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>301 Moved</title>
</head>
<%@ page import="org.apache.catalina.util.RequestUtil" %>
<%
    // get the requested URI
    //String requestedLocation = request.getRequestURI();
    // original request
    String requestedLocation = RequestUtil.filter((String) request.getAttribute("javax.servlet.error.request_uri"));
    // rewrite to new location
    String newLocation = requestedLocation.replaceAll("^/OldApp", "/NewApp");
    // add query string
    String query = request.getQueryString();
    if (!query.isEmpty()) {
        newLocation = newLocation + '?' + query;
    }

    // 301 - permanent redirect
    response.setStatus(response.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", newLocation);
%>
<body>
    &rarr; <a href="<%=newLocation%>"><%=newLocation%></a>
</body>
</html>

WEB-INF/web.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

  <error-page>
    <error-code>404</error-code>
    <location>/index.jsp</location>
  </error-page>
</web-app> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM