Creating an .htaccess file allows you to customize and configure how your web server handles requests for your website. An .htaccess file gives you control over things like URL rewriting, access restrictions, and caching rules.
While .htaccess files provide a lot of power, they can also cause problems if not coded properly. This guide will teach you how to properly create an .htaccess file to avoid issues.
What is an .htaccess File?
An .htaccess file is an Apache server configuration file that provides directory-level configuration instructions. The .htaccess file allows you to set rules and customize how content in a directory or multiple directories is served without access to the main server configuration file.
Some key things you can control with .htaccess files include:
- URL rewriting and redirects
- Authentication and authorization
- Caching settings
- Server-side includes
- Error documents
- Content gzipping
Why Use an .htaccess File?
Here are some of the top reasons to use an .htaccess file:
- Fine-tune Website Behavior – The .htaccess file gives you granular control over how your web pages are displayed and delivered. This helps you optimize site speed and performance.
- No Access to Main Config – If you don’t have root access to edit the main Apache config file, .htaccess gives you a way to control site behavior. This is common with shared hosting.
- Implement Password Protection – Use .htaccess to control access to directories requiring authentication. This provides security without coding password systems yourself.
- Improve SEO – From URL rewriting to page caching, .htaccess rules help search engine crawlers index and serve pages faster for improved SEO.
How .htaccess Rules Work
The directives added to an .htaccess file are applied to the directory in which the .htaccess file is placed as well as all sub-directories. This allows you to create one parent .htaccess file with instructions that cascade to content throughout parts of your site.
The rules work by overriding the main server configuration on a per-directory basis. .htaccess files don’t allow you to do absolutely everything the main configuration file can, but they do provide extensive control.
Where to Place an .htaccess file
.htaccess files are placed inside the document root folder you want the rules to apply to. Typically, this means putting the file inside the public_html or www directory of your hosting account in the case of most shared hosting.
On some managed WordPress hosts that use security restrictions, there may be limitations on using .htaccess files in subdirectories. Always check your host documentation for guidance.
To implement sitewide rules, place a single .htaccess in the root directory. For section-specific configuration, use individual .htaccess files in subdirectories like:
example.com
|– .htaccess (main config)
|
|– section1
|– .htaccess (section1 config)
|– section2
|– .htaccess (section2 config)
How to Create an .htaccess File
Creating an .htaccess file takes only a minute or two depending on how many custom rules you want to set.
1. Use a Text Editor
.htaccess files are simply text files. You can create one using any text editor like Notepad or TextEdit. Avoid using word processors like Microsoft Word that add special formatting.
For Windows users, open Notepad and go to File > Save As. Change the “Save as type” dropdown to “All Files” so you can manually type the filename.
For Mac users, open TextEdit, then go to Format > Make Plain Text to strip styling before saving.
2. Begin with the Header
Start your .htaccess file by adding some key header information:
# .htaccess main file
<IfModule mod_rewrite.c>
RewriteEngine On
</IfModule>
This does a few things:
- Sets the file as the main .htaccess config
- Check if the rewrite module that enables many .htaccess rules is enabled
- Turns on the rewrite engine to parse the rules
3. Add Your Custom Rules
The majority of the file consists of whatever custom .htaccess rules you want to add, structured like so:
<IfModule mod_deflate.c>
# Compress text, HTML, JavaScript, CSS, and XML
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>
This is enabling gzip text compression for common web content types. Add whatever other rules you need for your site.
4. Save the File
Simply save your text file as .htaccess with the leading period. Make sure it is in the proper document root folder to take effect.
Once uploaded to your live site, give Apache a few seconds to reload and your new .htaccess rules will override the default system config!
This covers the basic process of how to properly create an .htaccess file for your site. Let’s look at some of the most useful .htaccess tricks to optimize your content.
Essential .htaccess Rules and Uses
The power of .htaccess comes from the wide range of rules and functions you can implement for your site. While you can achieve a lot of advanced configurations, these are some of the most popular uses:
URL Rewriting and Redirects
Controlling URLs is one of the most common .htaccess uses. Typically this involves rewriting ugly URLs to clean, SEO-friendly ones and setting up 301 redirects when URLs change.
# Rewrite example.com/products.php?id=blue-shoes as /products/blue-shoes
RewriteCond %{THE_REQUEST} /products\.php\?id=([^&\s]+) [NC]
RewriteRule ^ products/%1? [R=301,L]
# Redirect old URL to new one
Redirect 301 /oldpage.html https://www.example.com/new-page
Access and Authentication Control
Use the “Require” rules to only allow authorized visitors access to protected directories. This enables password protection without coding login systems.
Here is the code:
# Require login for directory
AuthType Basic
AuthName “Protected Area”
AuthUserFile /path/to/passwordfile
Require valid-user
Server-Side Includes (SSI)
SSI directives let you embed dynamic content like file stats, environment vars, and dynamic page pieces.
Copy this code:
<!–#echo var=”LAST_MODIFIED” –>
<!–#include virtual=”footer.html” –>
Custom Error Pages
Display custom pages when 400, 403, 404, 500, and other HTTP error status occur.
Copy this code:
ErrorDocument 404 https://example.com/404.html
Gzip Compression
Enable compression of common text-based content types to speed up page load times.
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/x-javascript application/javascript
</IfModule>
Blocking and Allowing
Use “deny” and “allow” to whitelist or blacklist visitors by IP, referrer URLs, user agents and more.
# Block IP address
Order allow,deny
Deny from 192.168.1.10
# Allow single IP address
Order deny,allow
Allow from 192.168.1.11
Common .htaccess Mistakes to Avoid
While extremely useful, .htaccess rules do come with certain pitfalls you should keep in mind:
Incorrect Syntax
Syntax mistakes like missing brackets or directives are one of the most common issues. Remember that .htaccess uses a different syntax than the main config file.
Always check for errors if your rules don’t work as expected. The easiest method is to temporarily rename your .htaccess file so it stops overriding the main config. Then any syntax errors will appear in your Apache error log once requests start hitting the server again without the broken rules.
Too Many Complicated Rules
Loading up your .htaccess with rule after rule can bog down the server with excess processing. Use simplification and consolidation to avoid slow parsing. Consider moving complex processes to a programming language instead.
Directives Not Allowed
Some web hosts limit what directives can be used to increase security and stability. For example, many hosts block php_value directives. Check what exactly your host supports before implementing certain .htaccess rules.
Caching Issues
Rules related to headers, compression and caching can sometimes get “stuck” due to quirks in how browsers save them. Clearing your browser cache after changes is always a smart step.
Follow best practices and validate your syntax to avoid these common .htaccess mistakes!
Conclusion
Learning how to create an .htaccess file opens up many ways to customize and enhance your Apache web server. From improving site speed and SEO to implementing security features, .htaccess brings a lot of power through a simple text file.
Just be sure to carefully test your rules before deployment, watch for syntax errors or disabled directives from your host, and tweak as needed. Used properly, .htaccess can simplify your administration tasks and eliminate the need to edit the core server config.