Removing PHP Extension from Website URLs
Guide on how to configure your web server (Apache/Nginx) to hide the .php extension from URLs for cleaner links.
Introduction
Instead of https://example.com/about.php, you want https://example.com/about. This looks professional and is better for SEO.
Apache (.htaccess)
Add the following to your .htaccess file in the root directory:
RewriteEngine On
# 1. Externally redirect /file.php to /file (SEO friendly)
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L]
# 2. Internally rewrite /file to /file.php (Server handling)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
Nginx (nginx.conf)
Add this inside your server block or location block:
location / {
try_files $uri $uri/ @extensionless-php;
}
location @extensionless-php {
rewrite ^(.*)$ $1.php last;
}
# Process PHP files
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
}
Important Considerations
- Links: Update your HTML links manually. Change
<a href="contact.php">to<a href="contact">. - Conflicts: Ensure you don't have a folder named
contactand a file namedcontact.php, as this causes confusion.