Control file extensions with an .htaccess file

To control file extensions using an `.htaccess` file, you can use Apache's mod_rewrite module to rewrite URLs and enforce specific file extensions. Here's an example of how you can achieve this:

1. Create or edit the `.htaccess` file in the root directory of your website.

2. Add the following lines to the `.htaccess` file:

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

In the above example, the rule `^([^\.]+)$` matches any URL segment that doesn't contain a dot (.), which indicates a file extension. The rule then appends `.php` to the URL, effectively adding the PHP file extension.

You can modify the rule according to your needs. For example, if you want to enforce the `.html` file extension, you would replace `$1.php` with `$1.html`.

3. Save the `.htaccess` file.

After applying the changes, any URL segment without an extension will automatically have the desired extension appended. For example, if someone requests `example.com/page`, it will be internally rewritten to `example.com/page.php`. This way, the server can serve the appropriate file.

Remember to ensure that the mod_rewrite module is enabled on your Apache server. Additionally, make sure that you have AllowOverride set to at least FileInfo or All in the appropriate Apache configuration to allow the use of `.htaccess` files.

  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

Changing PHP settings in an .htaccess file

To change PHP settings using an `.htaccess` file, you can use the `php_value` directive. This...

How can I redirect and rewrite my URLs?

To redirect and rewrite URLs, you can use a combination of server configuration and URL rewriting...

Deny access to a site with an .htaccess file

To deny access to a site using an .htaccess file, you can use the `Deny` directive in combination...

Force your site to load securely code for .htaccess

To force your website to load securely using the .htaccess file, you can add the following code...

Prevent image hotlinking .htaccess

To prevent image hotlinking using `.htaccess`, you can add the following code to your `.htaccess`...