25

With regards to the forward slash "/" when giving a regex to RewriteRule or RewriteCond, or anything else related to .htaccess in particular, is there a need to escape the forward slash?

Here is an example of what I am trying to achieve

RewriteEngine on
RewriteOptions inherit

RewriteBase /uk-m-directory/
RewriteRule ^(region|region\/|regions\/)$ regions [R=301,L]
RewriteRule ^(county|county\/|counties\/)$ counties [R=301,L]
RewriteRule ^(city|city\/|cities\/)$ cities [R=301,L]

The above works fine, and it continues to work fine when I remove the backslashes as shown below

RewriteEngine on
RewriteOptions inherit

RewriteBase /uk-m-directory/
RewriteRule ^(region|region/|regions/)$ regions [R=301,L]
RewriteRule ^(county|county/|counties/)$ counties [R=301,L]
RewriteRule ^(city|city/|cities/)$ cities [R=301,L]

Which one is the correct way? Are they both wrong? Is there any special reason the forward slash should be escaped, or shouldn't?

My guess is that the forward slash does not need to be escaped because it isn't a special character, as far as I know. But I just want to be sure.

In case you're wondering the point of this code, it redirects city, county, and region (with or without a forward slash) to their plural equivalents. Furthermore if the plural has a forward slash it removes the forward slash.

Makoto
  • 104,088
  • 27
  • 192
  • 230
TrainTC
  • 253
  • 1
  • 3
  • 5

1 Answers1

28

No, you do not have to escape slashes. Forward slashes don't have any special meaning in regular expressions.

The one common character that has bitten me in the past is ? in query strings. That one you do have to escape.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thank you very much John for the quick reply =D A quick suppliment question John, if you don't mind, relating to your "?" comment. I know it has to be escaped (the questionmark) but what if it is on the right hand side of the rule? Say for example "RewriteRule ^/([a-z0-9]+)$ /index.php?query=$1" the questionmark on the righthand side (index.php?) does that have to be escaped? I know that it doesn't have to be, but you know, just making sure. – TrainTC Aug 28 '10 at 16:23
  • Correct again. Only on the left side. – John Kugelman Aug 28 '10 at 16:35