What are the best practices for structuring and configuring a .htaccess file in PHP to ensure it functions as intended?

When structuring and configuring a .htaccess file in PHP, it is important to follow best practices to ensure it functions as intended. This includes properly setting up redirects, protecting sensitive files, and improving website security. One common practice is to use mod_rewrite to create clean URLs and redirect users to the correct pages.

# Enable mod_rewrite
RewriteEngine On

# Redirect to www.example.com
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

# Protect sensitive files
<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
  Order Allow,Deny
  Deny from all
</FilesMatch>

# Prevent directory listing
Options -Indexes