Search code examples
php.htaccessmod-rewriteurl-rewritingpreg-match

How to allow use of dot in rewriting users profile page using htaccess and php


I have encountered a problem in trying to rewrite users profile page with usernames containing a full stop.

First of all, i applied this rewrite rule to my htaccess file;

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_]+)$ profile.php?tg_u=$1 [NC,L]
RewriteRule ^([^.]+)$ $1.php [NC,L]

actually, the rewrite rule worked when accessing users with username containing only letters and username containing a number and underscore(_) but when trying to access users with username such as user.name i do get a 404 page error, i tried changing previous preg_match to this preg_match(a-zA-Z0-9_.) and later to this preg_match(a-zA-Z0-9_.) on my htaccess (rewrite rule) but i noticed that when i want to access my site in localhost, the profile.php page is been shown as index page, i later then use this preg_match(a-zA-Z0-9.) on my htaccess file but still encounter the same problem.
I will be very grateful to know why i encounter this problem and also how to fix it.


Solution

  • You can use:

    RewriteEngine On
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteRule ^([a-zA-Z0-9_.]+)$ profile.php?tg_u=$1 [NC,L]
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^([^.]+)$ $1.php [NC,L]
    

    -d If the request is not a directory, and -f not a valid file name.
    And I added a test not to rewrite to php a page that does not exist.