Xenos
Xenos

Reputation: 3507

Exact match with RewriteRule without regex

I have the following htacces to rewrite a precise URL (views/index.php to views/index.xml):

RewriteEngine On
RewriteRule ^/views/index\.php$ /views/index.xml [L]

It's way too easy to forget the \ and type ^/views/index.php$, allowing /views/indexXphp and /views/index/php instead of only /views/index.php.

Using an exact match instead of a regex is fine for my case, so would be a way to tell Apache that for all RewriteRules below / for this RewriteRule, the dot means a . not any character so the dot is not escaped.

So, is there a way to have the exact match /views/index.php without the need to escape the dot?

Upvotes: 3

Views: 9846

Answers (3)

DustWolf
DustWolf

Reputation: 595

Unlike the accepted answer, the following solution worked for me:

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/(source)$
RewriteRule ^(.*)$ destination [R=301,L]

Upvotes: 0

anubhava
anubhava

Reputation: 786136

As Amal commented below your question that dot in regex means any character and since RewriteRule used regular expressions for URI pattern hence you will need to escape dot to make it match literal dot.

However in mod_rewrite rules there is way you can use RewriteCond to make it match literal strings without regular expressions using = sign before matching patten:

Here is an example of your translated rule:

RewriteCond %{REQUEST_URI} =/views/index.php
RewriteRule ^ /views/index.xml [L]

Upvotes: 7

zx81
zx81

Reputation: 41848

Yes, you can match /views/index.php without escaping the dot.

For instance, you can use /views/index[.]php, where the dot lives in a character class.

Also, many regex tokens allow you to match the dot, without specifically requiring a period. For instance,

  • . would match a period
  • [[:punct:]] would match a period
  • \D (not a digit) would match a period
  • \S (not a whitespace character) would match a period
  • (?![-/])[--/] would only match a period (this is a particularly perverse regex based on a small range of the ASCII table)

Upvotes: 0

Related Questions