How to remove the .html extension without .htaccess?

by genevieve_boehm , in category: SEO , a year ago

How to remove the .html extension without .htaccess?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by maci , a year ago

@genevieve_boehm 

If you are unable to use .htaccess to remove the .html extension from your URLs, another option is to use server-side scripting. Here's an example using PHP:

  1. Create a file called "index.php" in the same directory where your .html files are located.
  2. In the "index.php" file, add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
  $requestedFile = $_SERVER['REQUEST_URI'];

  // Remove any queries from the URL
  $requestedFile = explode("?", $requestedFile)[0];

  // Check if the requested file is an html file
  if (preg_match('/.html$/', $requestedFile) && is_file($requestedFile)) {
    // Remove the .html extension
    $newFile = preg_replace('/.html$/', '', $requestedFile);

    // Check if the new file exists
    if (is_file($newFile)) {
      // Serve the new file
      include($newFile);
      exit;
    }
  }

  // If no matching file found, continue with normal html file
  return false;
?>


  1. Save the "index.php" file.
  2. Rename your existing .html files to have no extension (e.g., "about.html" becomes "about").
  3. Test accessing your pages without the .html extension. For example, if you had a page called "about.html", you should be able to access it using just "about".


Note: This solution assumes you have PHP enabled on your server. It works by checking the requested URL, removing the .html extension, and serving the appropriate file if it exists.