Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I escape slash sign `/` in Apache `<If>` directive's regex?

I wanted to serve .xhtml files as

  • application/xhtml+xml if the browser says that it accepts it.
  • text/html otherwise

I tried doing it with mod_rewrite but it didn't work with Options -FollowSymLinks (see Why I do I get 403 Forbidden when viewing files affected by Apache RewriteRule if I have `Options -FollowSymLinks`?).

Then, I tried

<Files "*.xhtml">
    <If "%{HTTP:Accept} !~ /application\/xhtml\+xml/">
        ForceType text/html
    </If>
</Files>

But I get a syntax error: Failed to compile regular expression.

Meanwhile, I use this code...

<Files "*.xhtml">
    <If "%{HTTP:Accept} !~ /xhtml\+xml/">
        ForceType text/html
    </If>
</Files>

... which works, but I want to match the correct MIME type.

like image 376
Oriol Avatar asked Feb 28 '13 18:02

Oriol


People also ask

How do you escape a slash in regex?

You escape it by putting a backward slash in front of it: \/ For some languages (like PHP) you can use other characters as the delimiter and therefore you don't need to escape it.

Should slash be escaped in regex?

A slash symbol '/' is not a special character, but in JavaScript it is used to open and close the regexp: /... pattern.../ , so we should escape it too.

How do you use forward slash in regex?

There are two ways to create a regular expression instance. One way uses forward slash characters ( / ) to delineate the regular expression; the other uses the new constructor. For example, the following regular expressions are equivalent: var pattern1:RegExp = /bob/i; var pattern2:RegExp = new RegExp("bob", "i");


2 Answers

You could use an escape code like \x2F instead of the /.

like image 63
Qtax Avatar answered Sep 28 '22 08:09

Qtax


It looks like improving this is still under construction as of Apache 2.4. Apache team member "covener" recommends m#regexp# instead.

So your code would look like this...

<If "%{HTTP:Accept} !~ m#application/xhtml\+xml#">
like image 22
lkraav Avatar answered Sep 28 '22 10:09

lkraav