.htaccess is a configuration file for the Apache server, used to control and modify website settings. When placed in a directory, the Apache server detects and executes the instructions inside the .htaccess file.
.htaccess enables various features on the Apache server, such as custom error pages, password protection, URL redirection, and more. Below are some common uses:
You can use .htaccess to create custom error pages, providing visitors with a friendly error message when a URL is not found.
ErrorDocument 404 /error_pages/404.html
It’s easy to set up password protection for a directory, ensuring that only authorized users can access certain parts of your website.
AuthName "Admin Area" AuthUserFile /path/to/password/file/.htpasswd AuthType Basic require valid-user
The above code sets up a password-protected directory named “Admin Area”. When accessed, users will be prompted to enter a username and password. The file path points to a password file, and the authentication type is set to Basic.
The redirection feature allows you to direct visitors from one URL to another within your website.
Redirect /old_dir/ http://www.example.com/new_dir/index.html
order allow,deny deny from 155.0.2.0 deny from 123.45.6.1 allow from all
The above code blocks access from IP addresses “155.0.2.0” and “123.45.6.1” and allows access from all other IPs.
AddType text/html .htm0
This line binds the .htm0 file extension to the text/html MIME type, ensuring that browsers handle it correctly.
.htaccess is a powerful tool that allows you to configure various aspects of the Apache server, including security, redirection, and MIME types. Mastering its use in PHP development can greatly enhance the flexibility and security of your website.