Aug 16 2017
Aug 16, 2017

Change URL and hide PHP file with htaccess

Categorised in:

Are you curious about how you could hide your PHP file extension in URL? Let’s say you have an URL like this:

In this URL you can see the PHP user.php file and the user_id variable. There is a way to hide them and modify your URL like this:

This is just an example but there are multiple ways you can change it. You can write anything you want in your URL.

Changing your URL is possible with .htaccess file. Create a new file, if you don’t have it yet, in your main folder (htdocs or www) and name it .htaccess which means that you just gave an extension htaccess to your new file. It won’t have a name in your directory.

Now, to be able to change the URL we should activate the ReWriteEngine.

In .htaccess file write the following:

ReWriteEngine On

Which means that we just activated it. Bellow this line we should rewrite an existing URL. To do that we use this code:

RewriteRule ^profile/([^/.]+)?$ /user.php?user_id=$1 [L]

Where ([^/.]+) is the place where the user id will appear and $1 is the value number. In case we have another id or for example page in URL then the next value would be $2.

Let’s take another example. Let’s say we have:

To rewrite this URL we will use this code in .htaccess:

RewriteRule ^profile/([^/.]+)/page/([^/.]+)?$ /user.php?user_id=$1&page=$2 [L]

Where you can see that for each value ($1 and $2) there is a placeholder. So now we have two of ([^/.]+).

Profile/([^/.]+) is for user.php?user_id=$1
/page/([^/.]+) is for page=$2

There is a video on YouTube where you can see more details on how to use the ReWriteEngine.

Click here to watch now!