Mask a .php page with Mod Rewrite

David Carr

Htaccess Tutorials

Let's say you have a static website with various PHP files. These form the URL such as domains.com/about.php domain.com/serviers.php and you want to remove the .php from the URL.

You could create a folder for each page and then have the filenames named as index.php inside the folders. Whilst that would work its not a great solution.

Mod Rewrite is a great solution for this. Mod rewrite allows you to rewrite URLs for Apache-based applications.

The code in places inside a file called .htaccess that goes into your project root directory.

First check if mod rewrite is enabled on the server:

<IfModule mod_rewrite.c>

</IfModule>

Placing your code inside this check means it will only run when mod rewrite is enabled.

Next turn on the rewrite engine

RewriteEngine On

Optionally force HTTPS to be used

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

For the rewrite system a base it needed normally this is the root path of your project:

RewriteBase /

Now we are ready to set the URLs we want to use. We use RewriteRule followed by the name you want to use followed by the actual path to the .php page

RewriteRule ^about$ about.php
RewriteRule ^services$ services.php

With this setup going to /about will actually load /about.php the old url /about.php will still work but you would update all links to go to /about.

Putting it all together:

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

RewriteBase /

RewriteRule ^about$ about.php
RewriteRule ^services$ services.php

</IfModule>

 

 

 

 

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.