How to create clean url for profile users in htaccess while i already using for article which is working fine

Viewed 91

It is a very common question on the internet but unfortunately, I didn't find any solution yet. My issue is, I already using below codes, which is working fine for article purpose (site.com/my-first-article).

#remove .php    
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

#for pretty url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ blog.php?qTitle=$1 [NC,L]

But now i need (site.com/profile/user-name), when I copy and edit the code above for user profile it doesn't work.

#remove .php    
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

#for pretty url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ profile.php?username=$1 [NC,L]

I hope I defined the question well and some can understand my issue. Thanks for your time.

My output

enter image description here

1 Answers

To change the address site.com/profile.php?username=J0R1AN to site.com/profile/J0R1AN for example, you would need to use this code:

RewriteEngine On
# If user directly accesses /profile/[username]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?profile/(.*?)/?$ /profile.php?username=$1 [L]
# If user accesses /profile.php?username=[username]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /profile\.php\?username=([^\&\ ]+)
RewriteRule ^/?profile\.php$ /profile/%1? [L,R=301]

You can even keep using $_GET in the profile.php file

Source: https://www.taniarascia.com/rewrite-query-string-to-path-with-htaccess/

Related