Introducing the syntax and common usage examples of .htaccess.
.htaccess is a file used for configuring websites on an Apache server. It utilizes the Apache server modules mod_rewrite and mod_auth to control access to websites and redirect traffic.
The syntax of the .htaccess file is as follows:
- Comments: Lines starting with “#” are treated as comments and will not be processed by the server.
- Instruction: Each line consists of one instruction and one parameter, separated by a space.
- Directive block: Use directive blocks to organize related directives, enclose them with
and .
Here are some commonly used .htaccess directives and examples:
- Redirect:
- Redirect: Send one page to another page.
Example: Redirect /old-page.html /new-page.html - RewriteRule: Rewrite the URL using regular expressions.
For example: RewriteRule ^old-page.html$ new-page.html [R=301,L] - Prevent directory listing.
- Do not allow directory listing.
- Access control:
- Need: Establish access control rules.
For example: Require all denied. - MIME type:
- AddType: Adding MIME types.
For example: AddType application/x-httpd-php .php - Custom error pages:
- ErrorDocument: specifies the error page.
For example, ErrorDocument 404 /error404.html. - Enable GZIP compression:
- Enable GZIP compression with mod_deflate.
For example:
SetOutputFilter DEFLATE - Do not hotlink:
- RewriteCond: Checks the HTTP_REFERER to determine if Hotlinking is allowed.
For example: Check if the HTTP_REFERER is not empty, and if it does not start with http(s)://(www.)?yourdomain.com [NC], then the RewriteRule will be applied to deny access to images in jpg, jpeg, png, or gif format.
The above examples only cover a small part of what .htaccess can do. There are many other commands and features supported by .htaccess that can be configured based on specific needs.