What is the .htaccess file?
The .htaccess file is a configuration file used by the Apache web server. It allows you to configure various settings for your hosting package.
How do I create a .htaccess file?
Creating a .htaccess file is simple. You can use a text editor like Notepad or TextPad. First, check if there is an existing .htaccess file on your hosting. If there is, download it to your computer, make the necessary changes, and re-upload it to avoid disrupting existing settings.
If there isn't an existing file, open a new document in Notepad and save it as .htaccess. If your editor doesn’t support this format, save it as htaccess.txt and rename it later via an FTP client. Upload the .htaccess file to the root directory (httpdocs) or a subfolder within httpdocs using FTP.
What can I do with the .htaccess file?
-
Create Custom Error Pages:
You can enhance the appearance of error pages displayed to visitors. Common error pages include:
- 401 Authorization required: Displayed when users attempt to access password-protected pages with incorrect login details.
- 403 Forbidden: Shown when users try to access restricted files.
- 404 Not Found: Appears when a user tries to visit a non-existent page.
- 500 Internal Server Error: Indicates an issue with the hosting.
To customize these pages, save them on your server and specify them in your .htaccess file. For example, for pages named 401.htm and 404.html:
ErrorDocument 401 /401.html ErrorDocument 404 /404.html
If the pages are stored in a subfolder named "errorpages":
ErrorDocument 401 /errorpages/notauthorized.html ErrorDocument 404 /errorpages/notfound.html
This can also be done through the Plesk control panel.
-
Hide Directory Contents:
To prevent exposing directory contents when an index file is missing, add the following command to your .htaccess file:
Options -Indexes
Note: This setting is typically enabled by default in many hosting packages.
-
Block Specific IP Addresses:
To restrict access to your site based on specific IP addresses, add the following commands. For a single IP:
order allow,deny deny from IP allow from all
For multiple IPs:
order allow,deny deny from 125.30.5.1 deny from 125.30.5. allow from all
-
Redirects:
The .htaccess file can be used for redirection. For example, to redirect from an old page to a new location:
Redirect /oldpage.htm http://www.differentwebsite.com/new/file/location.html
For an old file in a subfolder:
Redirect /old/oldpage.htm http://www.differentwebsite.com/new/file/location.html
To redirect an entire directory:
Redirect 301 /olddirectory http://www.newsite.com/newdirectory
To redirect from a domain without "www" to the same domain with "www":
RewriteEngine on RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]