skip to Main Content

Have been trying to work this out for some hours now but not getting it right.

I have a site www.example.com/user.php?username=john
I use .htaccess to make it pretty like so www.example.com/user/john
I use the following .htaccess Rewrite rule and it works

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*/([a-zA-Z0-9_-]+)|([a-zA-Z0-9_-]+))$ ./user.php?username=$1 [L]

The problem

I have a profile page like www.example.com/profile.php?username=john
I also use the following .htaccess to make it good looking like www.example.com/profile/john

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*/([a-zA-Z0-9_-]+)|([a-zA-Z0-9_-]+))$ ./profile.php?username=$1 [L]

Now, this doesn’t work at all but when I remove the first rewrite rule (rule user.php) and place it after the second rewrite rule (rule profile.php) my profile page works, and vice versa,

So it’s basically whatever rule I place first is what determines what page I can access with my URL.

I need it to work for both pages. I will agree with you am not close to a beginner level at .htaccess rewrite.

Thanks in advance.

2

Answers


  1. Could you please try following. Since URLs are having their uniqueness so its better to check condition in their %{REQUEST_URI} value, I am checking if REQUEST_URI starts from user then go for 1 rule and if its starts with profile then go for another so there is no confusion(where I believe you tried very well kudos for that but since there is no segregation between conditions so hence its confusing Engine IMHO).

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} ^/user/([w-]+)/?$
    RewriteRule ^.*$ /user.php?username=%1 [NC,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} ^/profile/([w-]+)/?$
    RewriteRule ^.*$ /profile.php?username=%1 [NC,L]
    
    Login or Signup to reply.
  2. You can try below as well, checking first if the incoming request is neither a file nor a directory and then check for matching pattern.

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^user/([w-]+)/?$ /user.php?username=$1 [NC,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^profile/([w-]+)/?$ /profile.php?username=$1 [NC,L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search