How to Display Website URLs Without File Extension

Some website owners prefer URLs without file extensions, like .php, for aesthetic or SEO reasons. Instead of displaying URLs such as:

domain.com/index.php
domain.com/blog/index.php

They want cleaner URLs like:

domain.com/index
domain.com/blog/index

This tutorial will guide you through achieving this using .htaccess rules. These rules work well on servers running cPanel with the latest version of Apache.

Step-by-Step Guide

Add the following .htaccess code to your domain's root directory:

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

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

RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(([^/]+/)*[^.]+)\.php http://www.domain.com/$1 [R=301,L]

Explanation of the Code

  • Options +FollowSymLinks -MultiViews

    • +FollowSymLinksTells the server to follow symbolic links when resolving file paths.

    • -MultiViewsDisables Apache's MultiViews feature, which might conflict with the URL rewrites.

  • Redirect non- www to www

    Ensures all traffic is redirected to the www version of your domain:

    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

  • Rewrite URLs without extensions

    Maps URLs without extensions to their .php counterparts:

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

  • Remove .php from the URL

    Removes .php from the displayed URL and redirects it to the clean version:

    RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
    RewriteRule ^(([^/]+/)*[^.]+)\.php http://www.domain.com/$1 [R=301,L]

    Replace domain.com with your actual domain name.

What This Does

  • Converts URLs like:

    domain.com/index.php -> domain.com/index
    domain.com/blog/folder/ -> domain.com/blog/folder

  • Removes the trailing slash from directory URLs, ensuring cleaner links.

Important Notes

  • Domain Replacement

    Don’t forget to replace domain.com in the .htaccess code with your actual domain.

  • Trailing Slash

    The above configuration also removes trailing slashes from URLs. For instance:

    domain.com/blog/ -> domain.com/blog

  • SEO

    Some SEO experts suggest clean URLs without file extensions for better readability and search engine optimization. However, the impact varies depending on your website's structure and strategy.

With this setup, your website's URLs will appear cleaner and more professional, following modern best practices.