Skip to content

Commit

Permalink
Handle encoding challenges
Browse files Browse the repository at this point in the history
  • Loading branch information
donatj committed Apr 23, 2019
1 parent bbb8b3f commit ad12853
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/ApacheModRewriteGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,16 @@ public function generateRewrite( string $from, string $to, int $type ) : string
$fromQuery = $parsedFrom['query'] ?? '';
$toQuery = $parsedTo['query'] ?? '';

$fromPath = $parsedFrom['path'] ?? '';
$toPath = $parsedTo['path'] ?? '';
$fromPath = urldecode($parsedFrom['path'] ?? '');
$toPath = urldecode($parsedTo['path'] ?? '');

$output = '';

if( !$fromHost && $toHost ) {
throw new AmbiguousRelativeHostException('Unclear relative host. When the "FROM" URI specifies a HOST the "TO" MUST specify a HOST as well.');
}
if( $toHost && $fromHost !== $toHost ) {
$output .= 'RewriteCond %{HTTP_HOST} ^' . preg_quote($fromHost) . '$';
$output .= 'RewriteCond %{HTTP_HOST} ^' . preg_quote($fromHost, ' ') . '$';
$output .= "\n";
$prefix = "{$toScheme}://{$toHost}/";
} else {
Expand All @@ -43,12 +43,12 @@ public function generateRewrite( string $from, string $to, int $type ) : string
$explodedQuery = explode('&', $fromQuery);
foreach( $explodedQuery as $qs ) {
if( $qs !== '' ) {
$output .= 'RewriteCond %{QUERY_STRING} (^|&)' . preg_quote($qs) . '($|&)';
$output .= 'RewriteCond %{QUERY_STRING} (^|&)' . preg_quote($qs, ' ') . '($|&)';
$output .= "\n";
}
}

$output .= 'RewriteRule ^' . preg_quote(ltrim($fromPath, '/')) . '$ ' . $prefix . ltrim($toPath, '/') . '?' . $toQuery;
$output .= 'RewriteRule ^' . preg_quote(ltrim($fromPath, '/'), ' ') . '$ ' . $this->escapeSubstitution($prefix . ltrim($toPath, '/')) . '?' . $toQuery;

switch( $type ) {
case RewriteTypes::SERVER_REWRITE:
Expand All @@ -60,4 +60,8 @@ public function generateRewrite( string $from, string $to, int $type ) : string
throw new InvalidArgumentException("Unhandled RewriteType: {$type}", $type);
}

private function escapeSubstitution( string $input ) : string {
return preg_replace('/[-\s%$\\\\]/', '\\\\$0', $input);
}

}

0 comments on commit ad12853

Please sign in to comment.