2013-11-24 69 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

相關問題