[Drupal] Tips on configuring .htaccess for Drupal 8

| | 2 min read

What is htaccess ? The .htaccess file in Drupal is Powerful configuration file for web server. The .htaccess file loaded and executed when Apache server starts. .htaccess file in Drupal is used for varied functionalities such as Authentication, Redirect pages, Rewrite URL ,Directory Index and Limit access etc.

Authentication The authentication is used to protect the directory and prevent from unauthorized users. You can set up your directory is protected with following instruction.

AuthType Basic
AuthName "My Files"
AuthUserFile "/etc/htpasswd/.htpasswd"
Require valid-user
  • AuthUserFile : Location of your htpasswd file.
  • AuthType : What type of authentication used.
  • Require : Its allow access to valid users.
  • AuthName : Its Authentication name displayed on browser.

Redirect Pages You can redirect one page to another page or another url using mode using htaccess file.You can use the following rules to redirect custom error pages.

ErrorDocument 400 /400.html
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
ErrorDocument 502 /502.html
ErrorDocument 504 /504.html

Rewrite URL Rewrite URL is helpful for improve the site search availability. Rewrite url is used to create SEO based url. Check the following sample code to rewrite the URL.

RewriteRule ^cart/([0-9]+)/?$ cart.php?product_id=$1 [NC,L] # Handle product requests

Limit access You can allow or deny of your visitors based on visitors host address. Eg. as follows

Allows IP access to your website.

Allow from

Denys IP access to your website.

Deny from

Directory index The index.{extension} is the default page in every web server. We can change the this default page with the help of htaccess. You can set up your default page the the following code.

DirectoryIndex index.php index.html home.php index5.html