Showing posts with label url-rewriting. Show all posts
Showing posts with label url-rewriting. Show all posts

Monday, December 11, 2017

Can't rewrite Access_Control_Allow_Origin

Leave a Comment

I have one site that works like a cdn for my other sites.

I have added following to Web.config

<httpProtocol>   <customHeaders>     <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />     <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />     <add name="Arr-Disable-Session-Affinity" value="True" />   </customHeaders> </httpProtocol>  <rewrite>   <outboundRules>     <clear />     <rule name="AddCrossDomainHeader">       <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />       <conditions logicalGrouping="MatchAll" trackAllCaptures="true">         <add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?[a-zA-Z0-9-]*\.ap\.dk|(.+\.)?localhost\:[0-9]*))" />       </conditions>       <action type="Rewrite" value="{C:0}" />     </rule>   </outboundRules> </rewrite> 

I was inspired by answer #2 in here Access-control-allow-origin with multiple domains

But the rewrite of Access_Control_Allow_Origin does only work on localhost. On live site, it is not rewritten and then I get an error like this:

Failed to load https://aptestlogin.ap.dk//Widgets/Footer.html: The 'Access-Control-Allow-Origin' header has a value 'https://aptestproject.ap.dk' that is not equal to the supplied origin. Origin 'https://aptestcompany.ap.dk' is therefore not allowed access

In order to load this 'Footer.html' I'll have to clear cache in my brower, and repeat this if I open a another site that calls for this.

4 Answers

Answers 1

Try check regex pattern. Maybe forward slashes is unescaped // or something else.

https?:\/\/((.+\.)?[a-zA-Z0-9-]*\.ap\.dk|(.+\.)?localhost(\:[0-9]*)?) 

Answers 2

https://enable-cors.org/server_aspnet.html

Above will provide a solution for your matter.

Answers 3

Can you try like this

Install-Package Microsoft.AspNet.WebApi.Cors

Open the file App_Start/WebApiConfig.cs.

public static void Register(HttpConfiguration config)         {              config.EnableCors(); //add this           } 

Answers 4

Change

<match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" /> 

to

<match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern="*" /> 
Read More

Friday, October 20, 2017

Missing .aspx in URL in IIS 8

Leave a Comment

I've set up a new server with Server 2012 R2 and IIS and published an application to a new site. When I run the application in my development environment it shows the .aspx file extension in the URL but when I browse a published instance on the IIS server it removes the .aspx extension.

So somehow it has some sort of URL rewriting enabled out the box - how do I change this as I need it to be consistent with the development version. I installed the URL Rewrite extension to see if somehow any rules were configured but there are no rules defined.

Thanks!

3 Answers

Answers 1

You can configure your web.config file with rewrite rule (examplePage.aspx) like this:

<?xml version="1.0"?> <configuration>     <system.webServer>         <rewrite>             <rules>                 <rule name="examplePage.aspx Redirect" stopProcessing="true">                     <match url="^(.*\/)*examplePage\.aspx$" />                     <conditions logicalGrouping="MatchAll">                         <add input="{REQUEST_METHOD}" negate="true" pattern="^POST$" />                     </conditions>                     <action type="Redirect" url="{R:1}" redirectType="Permanent"/>                 </rule>             </rules>         </rewrite>     </system.webServer> </configuration> 

Hope that should work!

Answers 2

I have seen this behavior when creating a certain kind of web project in development. So it could be something installed that interferes. I guess you looked at the web.config already for anything, but if it is not there try the machine.config. Also, take a look in IIS itself, what is installed when you click on the root level (the one above the website).

Answers 3

Have you tried URL Rewrite. Let me know how it goes?

Read More

Tuesday, September 19, 2017

IIS rewrite rule not working in live environment

Leave a Comment

I have 4 servers in azure, 3 are load balanced and the 4th is for CMS purposes only.

SSL certificate has been added for the main website, but not for the sobdomain that the CMS is on.

I wrote a rule that should find any url that doesnt contain "backoffice" and match any other page to change it to https.

This works on regexr.com but for some reason doesnt work

<rewrite>         <rules>             <rule name="http to https" stopProcessing="true">                 <match url="(https?:\/\/(?!backoffice).*)" />                 <conditions>                     <add input="{HTTPS}" pattern="^OFF$" />                 </conditions>                 <action type="Redirect" url="https://www.WEBSITENAME.com{R:1}" />             </rule>         </rules>     </rewrite> 

Url Rewriting 2.1 is installed on all 4 servers and i have created a load balance set in azure for https.

going to https manually works fine (along with loadbalancing).

Additional information:

I've tried many rules, including the existing answer. I can see things happening, like assets being brought in as https, but the page itself does not redirect.

There are 2 load balance sets, one for port 80 and the other for port 443. I don't know if this is corect, or could be a potential cause in the redirect not happening.

2 Answers

Answers 1

Your rule should be like that:

<rule name="http to https" stopProcessing="true">     <match url=".*" />     <conditions>         <add input="{HTTPS}" pattern="^OFF$" />         <add input="{REQUEST_URI}" pattern="/backoffice" negate="true" />     </conditions>     <action type="Redirect" url="https://www.WEBSITENAME.com{R:0}" /> </rule> 

This rule will exclude requests with /backoffice path.

Also for issue of mixing content you need to fix your paths for css/js/images to relatives. Example:

<img src="/path/to/your/image.jpg"/> 

Another way to fix mixed content is create outbound rule, which will change your output HTML (replace http: to https:):

<rewrite>    ...    <outboundRules>     <rule name="Rewrite external references to use HTTPS" preCondition="IsHTML">       <match filterByTags="Script, Link, Img, CustomTags" customTags="HTML5Tags" pattern="^http://(.*)$" />       <action type="Rewrite" value="https://{R:1}" />     </rule>     <preConditions>       <preCondition name="IsHTML">         <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />       </preCondition>     </preConditions>     <customTags>       <tags name="HTML5Tags">         <tag name="Video" attribute="src" />       </tags>     </customTags>   </outboundRules> </rewrite> 

Answers 2

Using the previous answer as a starting point, i made a few minor changes, to use HTTP_HOST rather than REQUEST_URI for the pattern negation and it works.

<system.webServer>     <rewrite xdt:Transform="InsertIfMissing">         <rules>             <rule name="http to https" stopProcessing="true">                 <match url=".*" />                 <conditions>                     <add input="{HTTPS}" pattern="^OFF$" />                     <add input="{HTTP_HOST}" pattern="^backoffice\.WEBSITENAME\.com$" negate="true" />                 </conditions>                 <action type="Redirect" url="https://www.WEBSITENAME.com/{R:0}" />             </rule>         </rules>     </rewrite> </system.webServer> 
Read More

Monday, July 10, 2017

Rewrite sub folder dynamically with country code in WordPress using PHP

Leave a Comment

I know this question has been asked so many times but I didn't find any working solution or example which I can use to fix my problem.

I have been working on a client site. There are two similar sites, one for their own country and second for other countries visitors.

Their main site hosted in the root of server and second site hosted in the sub folder.

Now what I want is dynamic url rewrite for second site which is hosted into sub folder with the country code of the visiting user.

For e.g.

http://example.com
http://example.com/subfolder/

are the urls.

I want this http://example.com/subfolder/ to be changed into this http://example.com/country_code/ where country_code is visitor country code in ISO format getting through php function.

So if user is from United States the subfolder must be changed into us, the new url should be now http://example.com/us/.

I want this to work for all type of pages, whether its a page, post, category, tag or author page.

So again, http://example.com/subfolder/any-type-of-url/ => http://example.com/country_code/any-type-of-url/

Remember country_code is user/visitor country code in ISO format.

Let me know if someone needs more information on this. Thanks in Advance.

PS: I tried to achieve this using add_rewrite_rule() function available in WP.

1 Answers

Answers 1

You can do it by pretending rewrite rules through filter, based on user country ISO code. Please find code below.

function prepend_default_rewrite_rules( $rules ) {  // Prepare for new rules $new_rules = [];  // Set up languages, except default one, get user language code $user = get_current_user_id();   $language_slugs = (array) get_user_meta($user->ID, 'country_code');  // Generate language slug regex $languages_slug = '(?:' . implode( '/|', $language_slugs ) . '/)?';   // Set up the list of rules that don't need to be prefixed $whitelist = [     '^wp-json/?$',     '^wp-json/(.*)?',     '^index.php/wp-json/?$',     '^index.php/wp-json/(.*)?' ];  // Set up the new rule for home page $new_rules['(?:' . implode( '/|', $language_slugs ) . ')/?$'] = 'index.php';  // Loop through old rules and modify them foreach ( $rules as $key => $rule ) {      // Re-add those whitelisted rules without modification     if ( in_array( $key, $whitelist ) ) {          $new_rules[ $key ] = $rule;      // Update rules starting with ^ symbol     } elseif ( substr( $key, 0, 1 ) === '^' ) {           $new_rules[ $languages_slug . substr( $key, 1 ) ] = $rule;       // Update other rules     } else {          $new_rules[ $languages_slug . $key ] = $rule;      } }    // Return out new rules  return $new_rules; } add_filter( 'rewrite_rules_array', 'prepend_default_rewrite_rules' ); 
Read More

Tuesday, May 23, 2017

Handle the MEAN-stack application address without fragment '#'

Leave a Comment

Edit 1: Here is a mini code I made that reproduces the error. Please follow README.md to install.

Edit 2: Finally, I found one solution. Besides $locationProvider.html5Mode(true); ($locationProvider.hashPrefix('') is NOT necessary for me) and <base href="/" />, I need to add the follows in routes/index.js, rather than app.js. Then, we do NOT need to add anything more to app.js or nginx or apache like this thread mentions.

var express = require('express'); var router = express.Router(); var path = require('path'); ... ... router.get('*', function(req, res) {     res.sendfile('./views/index.html'); // load our public/index.html sendFile     // res.sendFile('index.html', { root: path.join(__dirname, 'views') }); // does not work }); 

One problem is, in the server console, it gives express deprecated res.sendfile: Use res.sendFile instead routes/index.js:461:9. But res.sendFile('index.html', { root: path.join(__dirname, 'views') }); can not help, it returns 404 error.

My express version is ~4.14.0... does anyone know how to fix that?

OP:

I develop in Mac with Apache a MEAN-stack application that can be requested by https://localhost:3000/#/home. In production with an NGINX server, the application can be requested by https://www.myapp.io/#/home. The fragment-identifier # is needed in all cases because of angular ui-router.

So I wanted to make pretty url without # (eg, https://www.myapp.io/home, https://localhost:3000/home) work. I have done the following:

  1. added $locationProvider.html5Mode(true); $locationProvider.hashPrefix('') in app.config(['$stateProvider'....

  2. added <base href="/" /> in index.html

As a result, https://localhost:3000/#/home changes automatically to https://localhost:3000/home in the browser bar, similarly for https://www.myapp.io/#/home.

However, directly entering https://localhost:3000/home or https://www.myapp.io/home in the browser will raise an error (I don't know how to turn previous <h1><%= message %></h1><h2><%= error.status %></h2><pre><%= error.stack %></pre> in error.ejs to error.html, so I don't have more details).

So now, the goal is to make https://localhost:3000/home and https://www.myapp.io/home work.

By following this thread, I added the follows to app.js:

app.use('/js', express.static(__dirname + '/js')); app.use('/dist', express.static(__dirname + '/../dist')); app.use('/css', express.static(__dirname + '/css')); app.use('/partials', express.static(__dirname + '/partials'));     app.all('/*', function(req, res, next) {     res.sendFile('index.html', { root: __dirname }); }); 

And in Apache of Mac, here is my httpd-vhosts.conf, after restarting apache, https://localhost:3000/home still returns an error.

<VirtualHost *:443>     ServerName localhost     DocumentRoot "/Users/SoftTimur"      SSLEngine on     SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL     SSLCertificateFile /etc/apache2/ssl/localhost.crt     SSLCertificateKeyFile /etc/apache2/ssl/localhost.key      <Directory "/Users/SoftTimur">         RewriteEngine on          # Don't rewrite files or directories         RewriteCond %{REQUEST_FILENAME} -f [OR]         RewriteCond %{REQUEST_FILENAME} -d         RewriteRule ^ - [L]          # Rewrite everything else to index.html to allow html5 state links         RewriteRule ^ index.html [L]          Options Indexes FollowSymLinks         AllowOverride All         Order allow,deny         Allow from all         Require all granted     </Directory> </VirtualHost> 

In production, here is the NGINX server block. After restarting NGINX, https://www.myapp.io/home still returns an error.

server {     listen 443 ssl;      server_name myapp.io www.myapp.io;      ssl_certificate /etc/letsencrypt/live/myapp.io/fullchain.pem;     ssl_certificate_key /etc/letsencrypt/live/myapp.io/privkey.pem;      ssl_protocols TLSv1 TLSv1.1 TLSv1.2;     ssl_prefer_server_ciphers on;     ssl_dhparam /etc/ssl/certs/dhparam.pem;     ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:EC$     ssl_session_timeout 1d;     ssl_stapling on;     ssl_stapling_verify on;     add_header Strict-Transport-Security max-age=15768000;      index index.html;      root /opt/myapp;      location / {         try_files $uri $uri/ /index.html;     }      location ~ /.well-known {         allow all;     }      location / {         proxy_set_header    Host                $host;         proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;         proxy_set_header    X-Forwarded-Proto   $scheme;         proxy_set_header    Accept-Encoding     "";         proxy_set_header    Proxy               "";         proxy_pass          https://127.0.0.1:3000;          # These three lines added as per https://github.com/socketio/socket.io/issues/1942 to remove sock$          proxy_http_version 1.1;         proxy_set_header   Upgrade $http_upgrade;         proxy_set_header   Connection "upgrade";     } } 

Could anyone help?

5 Answers

Answers 1

try this in your express server

var express = require('express'); var app = express();  app.get('*', function (req, res) { res.sendFile(__dirname + '/views/index.html'); }); 

and in your angular app:

$locationProvider.hashPrefix('!').html5Mode({     enabled: true }); $urlRouterProvider.otherwise('/'); 

and you still need the <base href="/"> in your index.html

let me know if this works for you

EDIT:

I just found your app in https://github.com/chengtie/mini-mean, looks like your app.use order is wrong. Please copy paste this in your express server and check if it's okay now. pastebin

Answers 2

This might useful stuff,

AngularJS routing without the hash '#'

Also, use this line in your express server file. app.use(express.static(path.join(__dirname, 'client folder')));

this will directly finds your index.html file in that views folder and loads it

Answers 3

  1. You don't need Apache or Nginx to run NodeJs in development, just node server.js is enough
  2. Express gave you that error because you are using a deprecated API res.sendfile please use res.sendFile (capital F)
  3. Some info for doing SPA:
    • When you have the '#' in your URL, the browser interpret it as a local reference and thus, won't send new request to the server
    • By enabling $locationProvider.html5Mode(true) you are now using html5 push state to navigate around your application history and (if I'm not mistaken you are happening to be using) angular effectively remove the '#' in url
    • Without the '#' (hash-bang) browser will interpret it as a new request and send it to server, so you have to map all requests from server to your SPA entry file
    • For exact steps of replicating this behavior, consult this article: https://scotch.io/tutorials/pretty-urls-in-angularjs-removing-the-hashtag (the base href in your entry file is important)

Answers 4

var path = require('path');

app.use(express.static(path.join(__dirname, 'public'))); app.get('*', function(req, res){ res.sendFile(path.join(__dirname, './', 'views', 'index.html')); });

the above code solved my issue for mean stack

Answers 5

If it's just about the #. You can remove it in Angular itself.

Just inject locationProvider at your app entry and set htmlMode to true. In your index.html set the baseUrl.

$locationProvider.html5Mode(true) 

And in you index.html add:

<base href="/" /> 

That will generate your urls without the #. Does that help?

Read More

Wednesday, April 5, 2017

Rewrite rule for name.123456.js in htaccess

Leave a Comment

I have this file in my webserver:

http://example.com/static/js/min/common.min.js 

Since all files inside /static/ are cached with CloudFlare's Edge Cache, I need a way to change the url with something like this, so if the file is modified, the new version will be automatically fresh served:

http://example.com/static/js/min/common.min.1234567890.js 

Where 1234567890 is the timestamp of the file's date modification. I already generate the filename according to the modification date, the issue I'm having is in the .htaccess file.

This works fine:

RewriteRule ^(.*)\.[\d]{10}\.(js)$ $1.$2 [L] 

That means that:

http://example.com/static/js/min/common.min.1234567890.js 

Is redirected to:

http://example.com/static/js/min/common.min.js 

But, that will catch all .js requests from the domain, I just want to catch .js requests from within /static/js/min/*.js -- but this is failing:

RewriteRule ^static/js/min/(.*)\.[\d]{10}\.(js)$ $1.$2 [L] 

What should the rule be like?

1 Answers

Answers 1

From your question,

You want to redirect

http://example.com/static/js/min/common.min.1234567890.js 

to

http://example.com/static/js/min/common.min.js 

So, How to do that

the .htaccess

First add

 RewriteEngine On  

To turn on the rewrite engine

Then the next important line comes

RewriteRule ^static/js/min/([^\d]*)(\d{10}).js$ static/js/min/$1js [L] 

Explanation

Set the path as static/js/min/

Then we use RegEx to take the string until a non digit. ([^\d]*).

That is common.min. is captured.

Now $1 is common.min.

Then to match the url, we use (\d{10}) to capture the digits.

That is 1234567890 is captured.

Now $2 is 1234567890 which we don't want anymore

Then redirect to

static/js/min/$1js 

Not that here we didn't added the . after the $1 because $1 ending with a . (common.min.)

So, the code will be

RewriteEngine On RewriteRule ^static/js/min/([^\d]*)(\d{10}).js$ static/js/min/$1js [L] 

Working Screenshot

My File Structure

enter image description here

The Address in Browser

enter image description here

Read More

Wednesday, August 17, 2016

How to rewrite base url in django to add logged in username in the url of all pages instead of app name?

Leave a Comment

I am working on django application and I have base url of application as below:

127.0.0.1:8000/myblog/page 

where 127.0.0.1:8000 is base url and myblog is App name and page is page name. So my requirement is to change the url to something like this without changing the internal code of my application:

127.0.0.1:8000/username/page 

Basically I want to change App name with user name in the URL. I have tried the solution given in this SO question. But it didn't helped much.

1 Answers

Answers 1

You can pass username into url regexp args and get request user from request class:
view:

def user_page(request, username):     try:         user = User.objects.get(username=username)     except User.DoesNotExists:         raise Http404     # or use shortcut get_object_or_404(User, username=username)     if request.user.username != user.username:         raise Http404     return render(request, 'templates/user_template', {'user':user}) 

urls:

url(r'^(?<username>\w+)/page/$', views.user_page, name='user_page') 

Note: username field not valid choice, if it not unique, it will produce an error when you get more then one user from User.objects.get(). Better use pk field for user page lookup.

But there is simpler way for building user page for request user. Just one url without keyword arguments, which response data for authenticated user:

view:

def user_page(request):     user = None     if request.user.is_authenticated():         user = User.objects.get(pk=request.user.pk)     return render(request, 'templates/user_template', {'user': user} ) 

urls:

url(r'^page/$', views.user_page, name='user_page') 

Now it return data based on request user or None if user is not authenticated

Read More

Thursday, August 4, 2016

Rewrite ASP.Net MVC homepage to another IP address

Leave a Comment

I have been trying to rewrite my homepage to another ip address in my ASP.Net MVC application. I have installed URL Rewrite and Application Request Routing modules in IIS. I have set the rewrite in my web.config, when i change the action type to redirect it works perfectly, but once i change it back to rewrite it does not work at all. I have changed the matching url to accept all requests, but still it does not work.

<system.webServer>         <rewrite>         <rules>         <clear />          <rule name="node" enabled="true" patternSyntax="Wildcard" stopProcessing="true">            <match url="*" />            <action type="Rewrite" url="http://255.255.255.255/" />          </rule>        </rules>      </rewrite>   </system.webServer> 

It seems like rewriting process has some conflicts with routing. How could i make the priority of rewrite higher?

3 Answers

Answers 1

Firstly you have to configure an Application Request Routing Server Farm that will consist of only one server (you should specify an IP for this server). After that you need to configure a global URL rewrite rule as described here.

Answers 2

The configuration of the URL Rewrite Module in the <rewrite> section is for internal URLs, and cannot rewrite domain or IP of the server:

IIS.NET: A Rewrite action replaces the current URL string with a substitution string. A substitution string must always specify the URL path (for example, contoso/test/default.aspx).

What you asked is not an url rewrite, but a reverse proxy. If you have an access to IIS, you can try its reverse proxy configuration, or simply create an HttpHandler, similar to this example. Next option can be http://urlrewriter.codeplex.com

Answers 3

Would there be config inheritance happening? If so, you can wrap the section you want with <location> to disable inheritence from parent app...

<location path="." inheritInChildApplications="false">   <system.webServer>     ...   </system.webServer> </location> 
Read More

Sunday, April 17, 2016

Add dynamic prefix in WordPress page url

Leave a Comment

I need to add dynamic prefix in page url.

You can help with how can I achieve this with Rewrite_API

Problem

In my WordPress website, I've few pages which I want to access using prefix before the page name in URL. For example, normally page is accessible using

http://example.com/page-name 

I want to add dynamic prefix(location) before the page name. So I want to access the page like below

http://example.com/country/state/page-name 

What I tried so far:

I tried to use below filter to add rewrite tag just before the page name in url.

add_action( 'init', array( $this, 'custom_rewrite_rules' ), 1, 0 );   /* * Rewrite page urls * adding prefix to page urls * @doc: http://stackoverflow.com/questions/17613789/wordpress-rewrite-add-base-prefix-to-pages-only */ function custom_rewrite_rules() {     global $wp_rewrite;     // add rewrite tag for location     $wp_rewrite->add_rewrite_tag( "%region%", '([^/]+)', 'region=' );      $wp_rewrite->page_structure = $wp_rewrite->root . '%region%/%pagename%';           }// end func 

Above action hook allows me to have dynamic page url in frontend and in backend. For example, I can see page urls are now

http://example.com/%region%/page-name 

What I need

As I have dynamic url's generated now, I want to replace %region% part of the url with the location string I want, It could be just country name or country/state name combination.

Thanks in Advance.

1 Answers

Answers 1

Change page link using wordpress filter

add_filter( '_get_page_link', 'custom_region_page_link', 10, 2 );  function custom_region_page_link( $link, $post_id ){     //$slug = get_post_meta( $post_id, 'key', true );     $link = str_replace('%region%', 'india', $link);     return $link; } 
Read More

Monday, April 11, 2016

Rewriting rule for &amp; in url

Leave a Comment

How can I setup a rule to replace &amp; with & in url?

This works: www.../home.asp?h=1&w=2

This fails: www.../home.asp?h=1&amp;w=2

1 Answers

Answers 1

For starters, it should be noted that you can access the messed up w parameter as follows:

Request.QueryString("amp;w"); 

However, I expect you would like something a little more eloquent :)

Assuming that you have access to the IIS URL Rewrite module, (IIS 7 and above), you can add some rules to web.config as follows:

<?xml version="1.0" encoding="UTF-8"?> <configuration>     <system.webServer>         <rewrite>             <rules>                 <rule name="One Bad Ampersand" stopProcessing="true">                     <match url="(.*)" />                     <conditions>                         <add input="{QUERY_STRING}" pattern="^([^&amp;]+)&amp;amp;([^&amp;]+)$" />                     </conditions>                     <action type="Rewrite" url="{R:1}?{C:1}&amp;{C:2}" appendQueryString="false" />                 </rule>                 <rule name="Two Bad Ampersand" stopProcessing="true">                     <match url="(.*)" />                     <conditions>                         <add input="{QUERY_STRING}" pattern="^([^&amp;]+)&amp;amp;([^&amp;]+)&amp;amp;([^&amp;]+)$" />                     </conditions>                     <action type="Rewrite" url="{R:1}?{C:1}&amp;{C:2}&amp;{C:3}" appendQueryString="false" />                 </rule>                 <rule name="Three Bad Ampersand" stopProcessing="true">                     <match url="(.*)" />                     <conditions>                         <add input="{QUERY_STRING}" pattern="^([^&amp;]+)&amp;amp;([^&amp;]+)&amp;amp;([^&amp;]+)&amp;amp;([^&amp;]+)$" />                     </conditions>                     <action type="Rewrite" url="{R:1}?{C:1}&amp;{C:2}&amp;{C:3}&amp;{C:4}" appendQueryString="false" />                 </rule>             </rules>         </rewrite>     </system.webServer> </configuration> 

What these rules do is check for an incoming &amp; in the query string and replace it with &. I do not think it is possible to come up with a generic rule to handle an arbitrary number of occurrences. But, I have established a pattern for up to 3 occurrences that you should be able to follow to add as many as needed.

It should be noted that if you wish to redirect the user's browser, you may do so by changing the type attribute in each action from Rewrite to Redirect.

Read More