Alex Rivera | Logout

How to redirect URLs with trailing slash to the corresponding ones without it?

Asked 2012-01-03T11:10:48.370
25

Spring MVC (3.0) considers URLs with and without trailing slashes as the same URL.

For example:

http://www.example.org/data/something = http://www.example.org/data/something/

I need to redirect the URL with trailing slashes

http://www.example.org/data/something/

to the URL without it:

http://www.example.org/data/something

I need to do this internally the application (so not rewrite rules via Apache, etc).

A way to do it is:

@ResponseStatus(value=HttpStatus.MOVED_PERMANENTLY)
@RequestMapping(value = "/data/something/")
public String dataSomethingRedirect(...) {
    return "redirect:/data/something";
}

but this has generally 2 problems:

  1. too many controllers
  2. problem with parameters: like wrong encoding

Question

Is there a way to intercept all the URLs and in case they have a trailing slash, redirect them to the relative one without slash?

Edit
Report

1 Answer

3

This usually works for me with URLRewriteFilter in Spring.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.2//EN" 
 "http://www.tuckey.org/res/dtds/urlrewrite3.2.dtd">
<urlrewrite>
    <rule>
         <note>Remove trailing slash for SEO purposes</note>
         <from>/**/</from>
         <to type="permanent-redirect">%{context-path}/$1</to>
    </rule>
</urlrewrite>
answered 2012-03-04T23:45:30.463

Your Answer