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:

  1. Comments: Lines starting with “#” are treated as comments and will not be processed by the server.
  2. Instruction: Each line consists of one instruction and one parameter, separated by a space.
  3. Directive block: Use directive blocks to organize related directives, enclose them with and .

Here are some commonly used .htaccess directives and examples:

  1. Redirect:
  2. Redirect: Send one page to another page.
    Example: Redirect /old-page.html /new-page.html
  3. RewriteRule: Rewrite the URL using regular expressions.
    For example: RewriteRule ^old-page.html$ new-page.html [R=301,L]
  4. Prevent directory listing.
  5. Do not allow directory listing.
  6. Access control:
  7. Need: Establish access control rules.
    For example: Require all denied.
  8. MIME type:
  9. AddType: Adding MIME types.
    For example: AddType application/x-httpd-php .php
  10. Custom error pages:
  11. ErrorDocument: specifies the error page.
    For example, ErrorDocument 404 /error404.html.
  12. Enable GZIP compression:
  13. Enable GZIP compression with mod_deflate.
    For example:
    SetOutputFilter DEFLATE
  14. Do not hotlink:
  15. 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.

bannerAds