How to remove file name from url using .htaccess?

Member

by maci , in category: SEO , 6 months ago

How to remove file name from url using .htaccess?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by laverna_hirthe , 6 months ago

@maci 

To remove the file name from a URL using .htaccess, you can use the following code:

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


This code assumes that you have Apache mod_rewrite enabled on your server.


Explanation:

  1. RewriteEngine On enables the rewrite engine.
  2. RewriteCond %{REQUEST_FILENAME} !-d checks if the requested URL is not a directory.
  3. RewriteCond %{REQUEST_FILENAME}.php -f checks if the requested URL with ".php" appended is a valid file.
  4. RewriteRule ^([^.]+)$ $1.php [NC,L] matches any URL that does not contain a dot (.) and redirects it to the corresponding PHP file. The [NC,L] flags mean "no case" (case-insensitive) and "last rule" respectively.


For example, if you have a file named "example.php" and you want to access it without the ".php" extension, you can use the URL "http://example.com/example". The .htaccess code will internally map this URL to "example.php" without revealing the file name in the URL.