Mod_rewrite several question marks

Sometimes the marketing department sent a mail program containing links with several question marks in them.

http://www.acme.com/site-page.jsp?content=mainpage?utm_campaign=somecampaign&utm_source=email 

This causes the application server to interpret mainpage?utm_campaign as a parameter, not just the mainpage . Is there a way to intercept these erroneous URLs in Apache and replace the second ? on & .

+6
source share
2 answers

You can put this code in your htaccess (which should be in the root folder)

 RewriteEngine On RewriteCond %{QUERY_STRING} ^(.+?)\?(.+)$ RewriteRule ^site-page\.jsp$ /site-page.jsp?%1&%2 [R=302,L] 

This code will be redirected

 /site-page.jsp?content=mainpage?utm_campaign=somecampaign&utm_source=email 

to

 /site-page.jsp?content=mainpage&utm_campaign=somecampaign&utm_source=email 

You now have these options:

  • content = mainpage
  • utm_campaign = somecampaign
  • utm_source = email

Note: feel free to change the 302 (temporary) redirect to 301 (permanent) redirect


EDIT

 RewriteCond %{QUERY_STRING} ^(.+?)\?(.+)$ RewriteRule ^(.*)$ /$1?%1&%2 [R=302,L] 
+5
source

I ran into a problem that more than one question mark may appear in my query strings. At first I started writing some rules for several use cases, but found that I had found the NE|No Escape flag.

 RewriteCond %{QUERY_STRING} ^(.*)\?(.*)$ RewriteRule (.*) $1?%1&%2 [NE,R=302,L] 

will do the trick.

This way, question marks will be deleted recursively. This increases the number of queries to the number of additional question marks, but reduces the number of rules to one.

I also changed the regex a bit. Thus, additional question marks at the beginning and at the end of the query line will also be replaced. This is not an ordinary case, but if we were faced with general cases, we would not need these rules at all; -)

0
source

Source: https://habr.com/ru/post/975541/


All Articles