5

I currently have a .htaccess file set up with this rule:

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

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

How could 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

Currently this brings up a 404 missing page error.

I have tried ^([a-zA-Z0-9\._-]+)$ user\.php?user=$1 [L] But this produces an internal error 500 (I think this is due to an infinite loop: user.php is designed to redirect to the homepage if no user is specified.)

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

Liam
  • 85
  • 1
  • 6

2 Answers2

1

. has no special meaning inside a character class, so there is no need to escape it.

If that doesn't help, try putting die("Test") right at the start of user.php. This will allow you to see if the error is coming from the rewrite, or the PHP file.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • If I simply add the . to the regex, then it does work but even mysite.com redirects to mysite.com/test.php?user=test.php The die('Test'); did prevent the loop though! Thanks – Liam Jun 23 '12 at 19:29
  • This is correct, for more info see http://perldoc.perl.org/perlrecharclass.html#Bracketed-Character-Classes – Anthony Hatzopoulos Apr 09 '14 at 19:13
1

First check if the requested URLs is 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]
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Gerben
  • 16,747
  • 6
  • 37
  • 56
  • 1
    Strangely, this RegEx didn't work for me until I put the dot from end to front like [.a-zA-Z0-9_-] Thank you. – kubilay Feb 20 '14 at 12:07
  • 2
    @kubilay the dash defines a range, it needs to be escaped in there like this: `RewriteRule ^([a-zA-Z0-9_\-.]+)$ user.php?user=$1 [L,QSA]` but since you moved it to the end it removes the error, technically you need to escape it. – Anthony Hatzopoulos Apr 09 '14 at 19:15