How to Remove .html and .php extension from Url using .htaccess

  • Home
  • Technical
  • How to Remove .html and .php extension from Url using .htaccess
Nov 5, 2021

Removing .php Extension from URL and Removing .html Extension from URL

Removing .php Extension from URL and Removing .html Extension from URL

Removing .php Extension from URL For example, You need to change the URL from http://test.com/test.php to
http://test.com/test1. Edit the .htaccess file and add the following settings.

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

Now, If the user accessed /test in the browser, it will show the from /test.php.But still, if any user typed the completed URL as http://test.com/test1.php, this will not redirect. Now you need to add some more rules to the
.htaccess file.

RewriteEngine on RewriteCond %{THE_REQUEST}
/([^.]+)\.php [NC] RewriteRule ^ /%1 [NC,L,R] RewriteCond
%{REQUEST_FILENAME}.php -f RewriteRule ^ %
{REQUEST_URI}.php [NC,L]

Removing .html Extension from URL For example, you need to convert your URL from http://test.com/test.html to
http://example.com/test. Edit .htaccess file and add the following settings:

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

Now, If the user accessed /demo in the browser, it will show the content from /test.html. Now, You may need to redirect users which typed complete URL as http://test.com/test1.html to the new URL http://test.com/test

RewriteEngine on RewriteCond %{THE_REQUEST}
/([^.]+)\.html [NC] RewriteRule ^ /%1 [NC,L,R] RewriteCond
%{REQUEST_FILENAME}.html -f RewriteRule ^ %
{REQUEST_URI}.html [NC,L]

Forcefully https redirection .htaccess file sample

RewriteEngine On
RewriteCond %{HTTPS} !=on
#RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
#Header always set Content-Security-Policy "upgrade-insecure-requests;"
#RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
#RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php

Leave a Reply