0

So I've been trying really hard to get rid of the trailing ? on the url to avoid SEO duplication. Basically i have a url like

www.example.com/some/thing?

and i need to redirect it to

www.example.com/some/thing

I have the following on my htaccess:

# Remove trailing ?
RewriteCond %{REQUEST_METHOD} (GET) [NC]
RewriteCond %{THE_REQUEST} \?\ HTTP [NC] 
#RewriteRule ([a-zA-Z0-9-/.=&:?]*)\?$ $1 [R=301,L]
RewriteRule ^(.*)$ $1 [r=301,l]

I tested my regex on line 4 using a tester and it got to work perfectly with the whole url. I then rigged the htacces to try and see what the variable THE_REQUEST returns and i noticed that my code is working but something is wrong. This is what i get in the rewrite.log with the code above:

127.0.0.1 - - [22/Jan/2013:16:08:09 --0800] [www.example.com/sid#2cb480][rid#eb90f8/initial] (2) init rewrite engine with requested uri /some/thing
127.0.0.1 - - [22/Jan/2013:16:08:09 --0800] [www.example.com/sid#2cb480][rid#eb90f8/initial] (3) applying pattern '^(.*)$' to uri '/some/thing'
127.0.0.1 - - [22/Jan/2013:16:08:09 --0800] [www.example.com/sid#2cb480][rid#eb90f8/initial] (4) RewriteCond: input='GET' pattern='(GET)' [NC] => matched
127.0.0.1 - - [22/Jan/2013:16:08:09 --0800] [www.example.com/sid#2cb480][rid#eb90f8/initial] (4) RewriteCond: input='GET /some/thing? HTTP/1.1' pattern='\?\ HTTP' [NC] => matched
127.0.0.1 - - [22/Jan/2013:16:08:09 --0800] [www.example.com/sid#2cb480][rid#eb90f8/initial] (2) rewrite '/some/thing' -> '/some/thing'
127.0.0.1 - - [22/Jan/2013:16:08:09 --0800] [www.example.com/sid#2cb480][rid#eb90f8/initial] (2) explicitly forcing redirect with http://www.example.com/some/thing
127.0.0.1 - - [22/Jan/2013:16:08:09 --0800] [www.example.com/sid#2cb480][rid#eb90f8/initial] (1) escaping http://www.example.com/some/thing for redirect
127.0.0.1 - - [22/Jan/2013:16:08:09 --0800] [www.example.com/sid#2cb480][rid#eb90f8/initial] (1) redirect to http://www.example.com/some/thing? [REDIRECT/301]

From what I understand of the log it is redirecting correctly but for some reason is appending the question mark at the end after the rewriterule when it's redirecting. Any idea on whats happening and how to fix this?

Also when i "unrig" it by uncommenting line 4 and commenting line 5 apache does not follow the rule as it is testing against /some/string and not against the whole url (URI+QUERY). How do I make apache check against whole url on RewriteRule instead of just the URI?

Note: The url is dynamic so i cant just hardcode a redirect.

bia.migueis
  • 1,996
  • 2
  • 15
  • 23

1 Answers1

0

From RewriteRule Directive

Modifying the Query String
...
When you want to erase an existing query string, end the substitution string with just a question mark.
...

So you must just append a ?

RewriteRule .* http://www.example.com/$0? [R,L]

Never test with 301 enabled, see this answer Tips for debugging .htaccess rewrite rules

Community
  • 1
  • 1
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198