Popular .htaccess Examples - KeyCDN Support (2024)

Updated on October 4, 2018

Popular .htaccess Examples - KeyCDN Support (1)

What is .htaccess?

The .htaccess file (also known as the Hypertext Access file) is used to define specific configurations for web servers running on Apache. This configuration file affects the directory that it is stored in as well as all subdirectories within that directory. For example, if the .htaccess file is located within your root directory, it will affect the entire site. On the other hand, if the file is located in a specific directory it will only affect that directory and any subdirectories within it.

Some CMS platforms such as WordPress and Drupal also come with .htaccess files to allow you to specify certain configurations that are applicable solely to that site. The .htaccess file can be used to achieve a variety of things including:

  • Performing redirects
  • Customizing error pages
  • Restricting users based on IP
  • Adding MIME types
  • Setting HTTP headers
  • Password protecting certain folders

The .htaccess file can be used to achieve much more, however the above list is amongst the most popular uses of .htaccess. The section below will outline various .htaccess examples and how they can be used within your own site.

.htaccess examples

There are a vast amount of configuration possibilities that can be achieved within the .htaccess file. The list below is a few of the more commonly used examples.

1. Redirect users to a specific error page

Based on the status code that a particular file or page returns, you can redirect the user to a custom error page. The example below shows a few variations that you can use. Each one dependant upon the status code that is returned.

ErrorDocument 403 /forbidden.htmlErrorDocument 404 /notfound.htmlErrorDocument 500 /servererror.html

2. Adding a custom header and value

Custom HTTP headers can also be added via the .htaccess file. There are a few syntax options, such as set which will replace any previous header that has the same name, add which will add the header even if another with the same name exists. Visit Apache's page header guide to learn more.

Header set X-Custom "Custom Value"

In the above example, the X-Custom text corresponds to the HTTP header that will be returned in the HTTP response while the Custom Value text corresponds to the value for this particular header.

3. Blocking users based on IP

For security purposes, you can block users based on their IP within the .htaccess file. In the example below, there are two IPs that are blocked. We can also decide to not include the last digit of the IP address which will result in all IPs that contain the first three digits being blocked.

order allow,denydeny from 255.x.x.xdeny from 123.x.x.xallow from all

4. Blocking referrers (hotlink protection)

Blocking referrers, also known as hotlink protection, is a method used to block certain referrers from referencing your website's assets and thus stealing your bandwidth. Use the snippet below to define which domains aren't allowed to refer to your content and thus they will receive a 403 Forbidden error.

RewriteCond %{HTTP_REFERER} unwanteddomain\.com [NC,OR]RewriteCond %{HTTP_REFERER} unwanteddomain2\.comRewriteRule .* - [F]

Similar functionality can also be achieved via the KeyCDN dashboard. To learn how to implement hotlink protection in your KeyCDN Zone, visit our Zone Referrers guide.

5. Adding MIME types

MIME types define what a particular file extension refers to. Therefore, it is sometimes required to set this in your .htaccess file to inform the web server what type of file you are referencing. To see a full list of MIME types visit the MIME Types List.

AddType image/gif .gif .GIF

6. Leveraging browser caching

The .htaccess file can also be used to help improve website performance by leveraging browser caching. Each file type can be defined with a particular expires value. You can define a custom list of file types and change each of their expires value, however the following snippet is a good starting point.

## EXPIRES CACHING ##<IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType text/css "access 1 month" ExpiresByType text/html "access 1 month" ExpiresByType application/pdf "access 1 month" ExpiresByType text/x-javascript "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 1 month"</IfModule>## EXPIRES CACHING ##

7. Enabling Gzip

Enabling Gzip on your origin server helps improve the performance of your assets as they are compressed and thus can be delivered faster. You can define a custom list of MIME types to be Gzipped, however the example below is a good starting point. To learn more about the benefits of Gzip and how it works, read our Enable Gzip Compression article.

<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/vnd.ms-fontobject AddOutputFilterByType DEFLATE application/x-font AddOutputFilterByType DEFLATE application/x-font-opentype AddOutputFilterByType DEFLATE application/x-font-otf AddOutputFilterByType DEFLATE application/x-font-truetype AddOutputFilterByType DEFLATE application/x-font-ttf AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE font/opentype AddOutputFilterByType DEFLATE font/otf AddOutputFilterByType DEFLATE font/ttf AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE image/x-icon AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/xml</IfModule>

8. Denying HTTP request methods

There are several HTTP request methods that are used for achieving various outcomes. If there are certain HTTP methods that you do not want a user to employ on your website, you can deny them with .htaccess.

RewriteCond %{REQUEST_METHOD} !^(HEAD|OPTIONS|POST|PUT)RewriteRule .* - [F]

9. Performing 301 redirects

If you need to perform a 301 redirect for a page that has moved, this can be easily achieved with .htaccess. Simply use the snippet below which takes the first URL (old link) and redirects it to the second URL (new link).

Redirect 301 https://yourwebsite.com/old-page https://yourwebsite.com/new-page

10. Enabling CORS

Enabling CORS is crucial for delivering static assets across various origins. The following snippet can be added to your .htaccess file in order to allow all origins to share resources. Otherwise, if this is not enabled and you origin is requesting resources from another origin, you will receive a CORS error. Read more about CORS in our How to Use CORS article.

<IfModule mod_headers.c> <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css|css|js|gif|png|jpe?g|svg|svgz|ico|webp)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch></IfModule>

The above .htaccess examples are a great starting point for those who are not yet familiar with using .htaccess, but still want to perform certain web server configurations. The .htaccess file has the ability to perform an array of tasks and is quite flexible to suit your website's needs. Although these .htaccess examples are a great starting point, you may be looking to perform some more advanced .htaccess configurations. For more on this topic consider checking out AskApache's .htaccess file guide article.

Popular .htaccess Examples - KeyCDN Support (2024)

FAQs

Popular .htaccess Examples - KeyCDN Support? ›

. htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

What to put in a .htaccess file? ›

. htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

How to check if .htaccess is enabled or not? ›

Test if . htaccess is working¶
  1. Test. ...
  2. <Directory /var/www/site/example.com/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>
  3. <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^.*$ htaccess_tester.php </IfModule>
  4. <Directory "/var/www/htdocs"> AllowOverride None.
  5. AllowOverride All.

Why is my .htaccess file not working? ›

The filename is misspelled or does not begin with a period

htaccess file included) then you must ensure that the filename is correct and that it begins with a period ( . ). Without the period at the beginning, Apache will ignore the file - the same goes for if the file is misspelled.

Can you have multiple htaccess files? ›

htaccess file is an Apache configuration file (HTTP) that is run by the web server of your Web Hosting plan. It allows you to define specific rules for a directory and all of its subdirectories. You can create multiple . htaccess files in the FTP space of your Web Hosting plan.

What is the basic htaccess file? ›

The . htaccess file's basic use is to allow or block access to a certain directory. You can configure it to selectively allow or disallow requests from a certain user. You can also redirect such users to a certain URL.

Is .htaccess necessary? ›

htaccess is not required for having a general website. That file simply allows you to make changes in the way your website behaves for example banning people from accessing your site or redirecting an old dead link to a new page. Some software like Wordpress requires settings in the . htaccess file (or httpd.

Where should the .htaccess file be located? ›

You will typically find the . htaccess file located within the root directory of your website. If you are not sure what a root directory is, then please refer to our article about finding the root directory of your domain. Usually, this file will be hidden as it may be used to compromise your account.

How to enable .htaccess file? ›

  1. How to Enable .htaccess in Apache. Step 1: Enable .htaccess. Step 2: Create .htaccess File. Step 3: Restrict Directory Listings.
  2. Why Configure an Apache . htaccess File and How? Custom Error Pages. Redirections. Blocking Traffic. Allow Specific IP Addresses. Block IP Addresses. Cross-Origin Resource Control. mod_rewrite.
Jun 20, 2024

How to find errors in htaccess? ›

Follow the steps below to activate the web pages:
  1. Access the main root directory of your website and look for the . htaccess file. ...
  2. Add or edit the following line: ErrorDocument 404 /error404. ...
  3. Specify the error code, followed by a space, then the path and filename of the . ...
  4. Save the .

How do I manually create a htaccess file? ›

htaccess file manually:
  1. Navigate to the WordPress root installation folder (public_html or www). ...
  2. Click the + File button in the upper-left corner to create a new file.
  3. Name the file . ...
  4. Open the file for editing.
Mar 20, 2024

How do I fix a corrupt .htaccess file? ›

The solution to fix a corrupted . htaccess file in WordPress is:
  1. First, access your website's FTP server using an FTP client like FileZilla or Cyberduck.
  2. Locate the . ...
  3. Rename the . ...
  4. Create a new . ...
  5. Click on the “Save Changes” button, which will automatically generate a new . ...
  6. If you had custom code in your old .

How do you edit the .htaccess file? ›

How To Edit An . htaccess File - Edit htaccess file in cPanel's File Manager
  1. Edit the file on your computer and upload it to the server via FTP.
  2. Use an FTP program's "Edit" mode that allows you to edit a file remotely.
  3. Use SSH and a text editor to edit the file.
  4. Use the File Manager in cPanel to edit the file.

What is the max execution time of htaccess? ›

htaccess File. By default, the max_execution_time is usually set to 30 seconds. If your PHP scripts need more time, then you need to edit the value in the .

What is the content of the htaccess file? ›

htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Can you have multiple databases on the same server? ›

Multiple databases can be configured on the same server when a Concurrent User License has been purchased, as this type of license is single server. When there is a deployment requirement for running a database on another server , additional license needs to be purchased.

Where should I put a .htaccess file? ›

htaccess file should be placed in the web root directory specific to that particular website. If you followed the prerequisites, your web root directory will be in the following location: /var/www/ your_domain /. htaccess .

What is the use of htaccess file in SEO? ›

6 uses of the . htaccess file in search engine optimization
  1. Creating user-friendly URLs with the .htaccess file. ...
  2. Allow or deny access to your website. ...
  3. Password protect directories. ...
  4. Improvement of indexing and crawling. ...
  5. Creating Redirects. ...
  6. Faster Page Speed.

What is the basic .htaccess file in WordPress? ›

The .htaccess is a distributed configuration file, and is how Apache handles configuration changes on a per-directory basis. WordPress uses this file to manipulate how Apache serves files from its root directory, and subdirectories thereof. Most notably, WP modifies this file to be able to handle pretty permalinks.

Is the htaccess file readable? ›

This directory contains an . htaccess file that is readable.

htaccess files are designed to be parsed by web server and should not be directly accessible. These files could contain sensitive information that could help an attacker to conduct further attacks. It's recommended to restrict access to this file.

Top Articles
Latest Posts
Article information

Author: Terrell Hackett

Last Updated:

Views: 6209

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Terrell Hackett

Birthday: 1992-03-17

Address: Suite 453 459 Gibson Squares, East Adriane, AK 71925-5692

Phone: +21811810803470

Job: Chief Representative

Hobby: Board games, Rock climbing, Ghost hunting, Origami, Kabaddi, Mushroom hunting, Gaming

Introduction: My name is Terrell Hackett, I am a gleaming, brainy, courageous, helpful, healthy, cooperative, graceful person who loves writing and wants to share my knowledge and understanding with you.