views:

65

answers:

1

I am very sorry if this question has been asked before, I have searched but I am still quite unsure.

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]

I just want to know which one is the correct way? Or are they both wrong? Is there any special reason the forward slash should be escaped? Or shouldnt?

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.

By the way incase 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.

Many thanks,

Amin.

A: 

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
Thank you very much John for the quick reply =DA 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
Correct again. Only on the left side.
John Kugelman