Ardit Hyka
Ardit Hyka

Reputation: 784

Rewrite rule on .htaccess with pattern match containing dot character is not working

Im creating a site with htaccess and one of the following it's not working by bringing up an error in the browser:

The page isn't redirecting properly

The rewrite rule line is:

RewriteRule ^([a-zA-Z0-9-_\.]+)$      index.php?user=$1   [NC,L]

I'm using it to get user profile in a get variable, the problem seems to be solved if the dot character is removed like this:

RewriteRule ^([a-zA-Z0-9-_]+)$      index.php?user=$1   [NC,L]

But i need the username format to contain the dot character.

Examples of how it should work:

http://www.example.dev/john.88     >>>  index.php?user=john.88
http://www.example.dev/johnsmith   >>>  index.php?user=johnsmith
http://www.example.dev/john_smith  >>>  index.php?user=john_smith

Thanks in advance.

Upvotes: 1

Views: 916

Answers (1)

anubhava
anubhava

Reputation: 785126

With DOT in pattern it will indeed cause infinite loop as rewritten URI /index.php also matches your pattern.

To fix this you need RewriteCond:

# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([\w.-]+)/?$ index.php?user=$1 [QSA,L]

Also note your regex pattern can be shortened by using \w which is equivalent of [a-zA-Z0-9_]

Upvotes: 1

Related Questions