How to hide extension and containing folder with .htaccess?

by , in category: SEO , 8 months ago

How to hide extension and containing folder with .htaccess?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer


by mabelle , 7 months ago 

To hide the file extension and containing folder using .htaccess, follow the steps below:

  1. Create or locate the .htaccess file in the folder where you want to hide the extension and containing folder.
  2. Open the .htaccess file and add the following code:
RewriteEngine On

# Redirect requests for the file without the extension
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)/?$ $1.php [L]

# Redirect requests for the containing folder
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

  1. Save the changes to the .htaccess file.

This code uses Apache's mod_rewrite module to handle the URL rewriting.

The first section of the code hides the file extension by checking if a file with the extension .php exists for the requested URL. If it does, the extension is appended to the URL and the server considers it as a valid request.

The second section redirects requests for the containing folder by checking if the requested URL represents a directory. If it is, the trailing slash is removed using a 301 (permanent) redirect.

By following the above steps, the extension and containing folder should be hidden for URLs within the specified folder.