2013-11-24 39 views
2

在我的web.xml文件中,我配置:使用重定向,而不是向前<欢迎文件>

<welcome-file-list> 
    <welcome-file>index.xhtml</welcome-file> 
</welcome-file-list> 

这意味着,当我键入一个URL www.domain.comindex.xhtml文件被用来渲染。但是当我输入www.domain.com/index.xhtml时,结果是一样的。 它被称为重复内容? 这对我的项目来说不成问题,但是对于SEO来说却是一个大问题。 如何在输入网址www.domain.com时重定向到www.domain.com/index.xhtml页面,而不是让它执行转发?

+0

对“www.domain.com/index.xhtml”的请求是一样的,因为'index.xhtml'可能在您的webapps文件夹中是公开的。 –

+0

你是对的。但我只是想避免重复的内容。怎么做。你的意思是,现在我必须隐藏index.xhtml并编辑web.xml –

回答

2

的URL标记为重复的内容。是的,如果SEO很重要,你绝对应该担心这一点。

解决这个问题的最简单方法是在index.xhtml的头部提供一个所谓的规范URL。这应该代表偏好的URL,这是你的具体情况显然是一个与文件名:

<link rel="canonical" href="http://www.domain.com/index.xhtml" /> 

这样的http://www.domain.com将被索引为http://www.domain.com/index.xhtml。并且不会导致重复的内容了。但是,这并不会阻止最终用户能够书签/共享不同的URL。

另一种方法是将HTTP 301重定向配置为首选项的URL。理解302重定向的起源仍然被searchbots索引是非常重要的,但301重定向的起源不是,只有目标页面被索引。如果您要使用HttpServletResponse#sendRedirect()默认使用的302,那么您仍然会因为两个网址仍被编入索引而导致内容重复。

这是一个这样的过滤器的启示例子。只需将其映射到/index.xhtml上,并在URI不等于所需路径时执行301重定向。

@WebFilter(urlPatterns = IndexFilter.PATH) 
public class IndexFilter implements Filter { 

    public static final String PATH = "/index.xhtml"; 

    @Override 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
     HttpServletRequest request = (HttpServletRequest) req; 
     HttpServletResponse response = (HttpServletResponse) res; 
     String uri = request.getContextPath() + PATH; 

     if (!request.getRequestURI().equals(uri)) { 
      response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); // 301 
      response.setHeader("Location", uri); 
      response.setHeader("Connection", "close"); 
     } else { 
      chain.doFilter(req, res); 
     } 
    } 

    // init() and destroy() can be NOOP. 
} 
0

要删除重复的内容,请设计一个带有URL模式的过滤器/*。如果用户在根域比重定向到index.xhtml的URL。当有上返回完全相同相同的反应相同域的另一个URL

@WebFilter(filterName = "IndexFilter", urlPatterns = {"/*"}) 
public class IndexFilter implements Filter { 

    public void doFilter(ServletRequest req, ServletResponse resp, 
     FilterChain chain) 
     throws IOException, ServletException { 
    HttpServletRequest request = (HttpServletRequest) req; 
    HttpServletResponse response = (HttpServletResponse) resp; 
    String requestURL = request.getRequestURI().toString(); 
    if (request.getServletPath().equals("/index.xhtml") && 
       !requestURL.contains("index.xhtml")) { 
     response.sendRedirect("http://" + req.getServerName() + ":" 
       + request.getServerPort() + request.getContextPath() 
       +"/index.xhtml"); 
    } else { 
     chain.doFilter(req, resp); 
    } 
} 
} 
+0

'sendRedirect()'做了一个302而不是301.过滤器代码的剩余部分也不令人兴奋,虽然它的工作,它显然写由首发和几件事情可以做得更干净。 – BalusC

+0

谢谢@Masud,但我想问更多。这种现象是否称为重复内容? –

+0

我不认为他能够以正确的方式讲述关于搜索引擎优化的内容,因为他已经没有将301重定向到第一位。 – BalusC

相关问题