Escape character (.) In mod_rewrite regex

I currently have a .htaccess file with this rule:

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

works as expected: mysite.com/joe becomes mysite.com/user.php?user=joe

How can I change the regex to include periods in a possible username?

For example, I would like mysite.com/joe.bloggs to go to mysite.com/user=joe.bloggs

This currently causes a 404 error error.

I tried ^([a-zA-Z0-9\._-]+)$ user\.php?user=$1 [L] But this causes an internal error of 500 (I think this is due to an infinite loop: user.php intended to redirect to the main page if the user is not specified).

I am new to all of this (especially regex). Thanks for any help!

+4
source share
2 answers

First check if the requested URLs are not a file or folder. This will prevent the redirect loop for urls like /user.php

 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-zA-Z0-9_-.]+)$ user.php?user=$1 [L,QSA] 
+1
source

. It doesn’t have much meaning inside a character class, so there is no need to avoid it.

If this does not help, try putting die("Test") at the beginning of user.php . This will let you know if the error comes from a rewrite or a PHP file.

+1
source

All Articles