John Doe
John Doe

Reputation: 1043

Rewrite Rule to expect dots

I use this RewriteRule in my .htaccess

RewriteRule ^api/v1/([A-Za-z0-9-_,]+)$ api/v1/index.php?function=$1

I have tried several variations already, but I was unable to find a way to include dots into the regex expression.

Some sources here on SO, say that I can simply include "." right after my "," but some sources say I need to escape the dot with "." Neither has unfortunately worked so far.

Upvotes: 1

Views: 157

Answers (2)

anubhava
anubhava

Reputation: 785561

You can include dot in character class inside [..] however there are few issues with your rule:

  1. Hyphen must be at first or last position to avoid escaping.
  2. By including dot your pattern will also match index.php and since mod_rewrite runs in a loop it will make function query parameter as index.php. To avoid this situation you will need RewriteCond.
  3. [a-zA-Z0-9_] can be replaced with [\w]

Try this rule:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^api/v1/([\w,.-]+)/?$ api/v1/index.php?function=$1 [L,QSA,NC]

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111869

It seems you simply need to add dot without escaping

When I have the following files:

// .htaccess

RewriteEngine On

RewriteRule ^api/v1/([A-Za-z0-9-_,.]+)$ api/v1/index.php?function=$1 [QSA]

and

// api/v1/index.php

<?php

var_dump($_GET['function']);

and I run url http://mydomain/api/v1/something.more.something in my browser I get the following result:

string(24) "something.more.something"

so the whole match is passed to $_GET['function'].

It seems to work without any problem (as you see there's also dot inside the url and it is working)

Upvotes: 0

Related Questions