Forum Topic: Backslash in code

Forum: .htaccess Forum : Basics • Posted by Jeroen • Updated:

Jeff, I noticed that sometime you use a backslash in urls in the htaccess file and sometimes not. Is both possible or is there a best practice or should there always be a backslash or never?

Examples:

RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{HTTP_REFERER} !^http://example\.com [NC]
RewriteCond %{REQUEST_URI} !wp-(login|admin|content|includes|trackback)	[NC]
RewriteCond %{HTTP_USER_AGENT} ^-?$ [OR]
RewriteCond %{HTTP_REFERER} ^-?$ [OR]
RewriteCond %{HTTP_HOST} ^-?$
RewriteRule .* - [F,L]

and

RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} wp-comments-post.php
RewriteCond %{HTTP_REFERER} !^http://example.com [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule .* http://%{REMOTE_ADDR}/$ [R=301,L]

And a .co.id url should have two backslashes? dapurkobe\.co\.id ?

2 Replies to “Backslash in code”

Posted by Jeff Starr

Great question, and something I need to be more consistent about. When a backslash is used, the character is escaped and treated literally. Otherwise, the character is processed as normal. So for example, the dot is a literal period when escaped, and a wildcard character when not. So in this example:

example\.com

the string will match only “example.com”, whereas in this example:

example.com

the string will match any of the following:

example.com
example,com
exampleacom
examplebcom
exampleccom

..and so on for every character. So whether or not you escape the character depends on how closely you need things to match. In some cases not escaping is fine, but in general it is best practice to escape all known values.

Posted by Jeroen •

Clear Jeff, thanks.