Saturday 2 November 2019

.htaccess - Removing trailing question mark with htaccess



Can someone help me understand this code?




# Remove trailing ?
RewriteCond %{THE_REQUEST} ? HTTP [NC]
RewriteRule .? /%{REQUEST_URI}? [R=301,L]


Basically I have a site www.example.com that is generating a link to www.example.com/index.cfm? I need it to redirect to www.example.com for SEO duplication purposes. I managed to remove the index.cfm but the ? still stays there (www.example.com/?). The trailing slash is also removed just fine if it's the last character. I found this rule online but I'm getting a "RewriteCond: bad flag delimiters" alert in apache and it doesn't do anything.



I also have some pages like www.example.com/index.cfm?term=test for searching so I just want to get rid of the trailing question mark and not when I do have a query attached to it.




The error is in the RewriteCond. I need help understanding the condition and why it doesnt work not just the answer to it.



Just in case here is the entire htaccess:



RewriteEngine On
Rewritebase /

# remove trailing index.cfm
RewriteRule ^index.cfm(\?)?$ / [R=301,L]


# SEF URLs
SetEnv SEF_REQUEST false
RewriteRule ^[a-z\d\-]+/[a-z]\d+/? /index.cfm/$0 [NC,PT,QSA,E=SEF_REQUEST:true]
RequestHeader add SEF-Request %{SEF_REQUEST}e
RewriteCond %{HTTP:SEF_REQUES} ^true$ [NC]
RewriteRule . - [L]

# Remove trailing ?
RewriteCond %{THE_REQUEST} ? HTTP [NC]
RewriteRule .? ^%{REQUEST_URI}? [R=301,L]



NOTE: I did search online/stackoverflow before posting and did not find a solution to my problem.



EDIT: Also I noticed that my RewriteRule ^index.cfm(\?)?$ / [R=301,L] is removing the index.cfm even if it's not the last thing in the url resulting in a 404 when i try searching something (www.example.com/index.cfm?term=test) If someone could correct me and EXPLAIN that would be great. Thanks you.



EDIT2: www.example.com/index.cfm?term=test&a=dh&j=dhjsi should NOT be redirected.
www.example.com/a/b/d/f/h/w/d should not be redirected.
www.example.com/index.cfm? and www.example.com/index.cfm should be redirected to www.example.com.


Answer




RewriteCond %{THE_REQUEST} ? HTTP [NC] 
RewriteRule .? ^%{REQUEST_URI}? [R=301,L]


Isn't going to work, because ? is a reserved character for regular expressions and you'd need to escape it along with the space. Try:



RewriteCond %{THE_REQUEST} \?\ HTTP [NC] 
RewriteRule ^/?(index\.cfm)? /? [R=301,L]



Additionally, you want this rule under your # remove trailing index.cfm rule, and not at the very bottom.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...