5
(1)

Last Updated on April 15, 2021 by Amit

htaccess rewrite user urls

In this post post I will show you how to shorten a user URL on Apache server by htaccess.

Assuming you have a long user URL that looks something like the following:

/user.php?username=foobar

And you want to shorten this URL to :

/foobar

The shorter version is easier to remember ,type and search engine friendly.
You can easily do this using RewriteRule in htaccess.
You just need to rewrite the “short/new version” to the “old/longer one” . This can be done very easily with just a single RewriteRule line.

The following RewriteRule will rewrite /foobar to /user.php?user=foobar


RewriteEngine on
RewriteRule ^foobar /user.php?user=foobar [L]

The rule applies only to a single URL path, to re5the user URL dynamically you could use :


RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+) /user.php?user=$1 [L]

This RewriteRule rewrites any user path that matches the pattern (.*). The RewriteConds in the rule above are important as it prevents your existing files and folders from being rewritten.

With the above rule you will be able to access your old long user URL using a new short URL. So instead of going to /user.php?user=username you can simply go to /username .

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.