Randy Randy - 3 months ago 24
PHP Question

PHP Pretty URLs combination of two mod_rewrite rules?

I have this .htaccess code in the root folder to replace this url:

localhost/mysite/profile.php?username="someone"
to become
localhost/mysite/someone
.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /mysite/profile.php?username=$1


This is working fine but what I want is to include subpages like for example the about page to be
localhost/mysite/about
instead of
localhost/mysite/about.php
. And the subpages are in the root folder too.

How can I achieve these two rewrites?

Answer

You can have this code in mysite/.htaccess:

RewriteEngine On 
RewriteBase /mysite/

# add .php internally to files
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

# handles profile URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/?$ profile.php?username=$1 [L,QSA]
Comments