惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LangChain Blog
G
Google Developers Blog
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
Vercel News
Vercel News
Stack Overflow Blog
Stack Overflow Blog
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
DataBreaches.Net
C
Check Point Blog
月光博客
月光博客
MongoDB | Blog
MongoDB | Blog
F
Fortinet All Blogs
MyScale Blog
MyScale Blog
WordPress大学
WordPress大学
M
MIT News - Artificial intelligence
博客园_首页
S
SegmentFault 最新的问题
The Cloudflare Blog
NISL@THU
NISL@THU
T
The Exploit Database - CXSecurity.com
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
H
Help Net Security
大猫的无限游戏
大猫的无限游戏
Spread Privacy
Spread Privacy
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
U
Unit 42
S
Schneier on Security
博客园 - 司徒正美
Help Net Security
Help Net Security
O
OpenAI News
PCI Perspectives
PCI Perspectives
T
Troy Hunt's Blog
Microsoft Azure Blog
Microsoft Azure Blog
Forbes - Security
Forbes - Security
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
News | PayPal Newsroom
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Threatpost
V
Vulnerabilities – Threatpost
美团技术团队
P
Palo Alto Networks Blog
TaoSecurity Blog
TaoSecurity Blog
V2EX - 技术
V2EX - 技术
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
I
InfoQ

DigitalOcean Community Tutorials

Mastering grep with Regular Expressions for Efficient Text Search It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go How To Set Up Time Synchronization on Ubuntu How To Use Struct Tags in Go apt-key Deprecation: Add Repositories with GPG on Ubuntu Linux ps Command: 20 Real-World Examples Python struct.pack and struct.unpack for Binary Data Deadlock in Java: Examples, Detection, and Prevention How To Use Find and Locate to Search for Files on Linux Structured Resume Skill Extraction Using Mistral-7B Inference How to Use the Python Main Function How to Set Up NemoClaw on a DigitalOcean Droplet with 1-Click Build an End-to-End RAG Pipeline for LLM Applications From Single to Multi-Agent Systems: Key Infrastructure Needs Back Up Data to Object Storage Using Restic How to Generate Videos with LTX-2.3 on DigitalOcean GPU Droplets How To Install LAMP Stack (Apache, MySQL, PHP) on Ubuntu How to Download Files with cURL How To Use Variadic Functions in Go Generate UUIDs with uuidgen on Linux How To Use EJS to Template Your Node Application How to Install Node.js on Ubuntu (Step-by-Step Guide) MongoDB Indexes: Improve Query Performance with Node.js LLM Tool Calling with DigitalOcean AI Platform and Databases What are Text Diffusion Models? - An Overview Crafting a Game from Scratch with GPT-5.4 Building Long-Term Memory in AI Agents with LangGraph and Mem0 How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 20.04 Build a GraphQL API in Go to Upload Files to Spaces How To Lint and Format Code with ESLint in Visual Studio Code Train YOLO26 for Retail Object Detection on DigitalOcean GPUs How To Work with JSON in MySQL How to Use the JavaScript .map() Method Building a Scalable App with MongoDB Using DigitalOcean's MCP Server How to Create an SSH Key in Linux: Easy Step-by-Step Guide Measure MySQL Query Performance with mysqlslap How To Use *args and **kwargs in Python 3 Nemotron 3 helped me find the perfect dish rack? A2A vs MCP - How These AI Agent Protocols Actually Differ How To Install and Manage Supervisor Docker Container Images with Watchtower on Ubuntu Getting Started with Qwen3.5 Vision-Language Models How To Create a New Sudo-Enabled User on Ubuntu How to Use Ansible to Install and Set Up Docker on Ubuntu How To Enable Remote Desktop Protocol Using xrdp on Ubuntu 22.04 How To Convert a String to a List in Python How To Check If a String Contains Another String in Python How to Read a Properties File in Python Python Command Line Arguments: sys.argv, argparse, getopt Mastering Grep command in Linux/Unix: A Beginner's Tutorial Understanding Python Data Types How to Implement a Stack in C With Code Examples Python os.system() vs subprocess: Run System Commands How To Install and Use Docker Compose on Ubuntu How to Add and Delete Users on Ubuntu How To Order Query Results in Laravel Eloquent How To Define and Use Handlers in Ansible Playbooks How To Install and Use SQLite on Ubuntu How To Install and Use Homebrew on macOS How To Manage DateTime with Carbon in Laravel and PHP How To Install Git on Ubuntu How To Install and Secure Redis on Ubuntu How To Build and Install Go Programs on Linux Using ldflags to Set Version Information for Go Applications How To Build a Node.js Application with Docker How To Add JavaScript to HTML How To Reset Your MySQL or MariaDB Root Password How To Add Images in Markdown How To Set Up a Production Elasticsearch Cluster with Ansible How To Set Up a Firewall Using firewalld on CentOS Understanding Systemd Units and Unit Files How To Set Up Replication in MySQL
How To Use the .htaccess File
Anish Singh Walia · 2012-07-13 · via DigitalOcean Community Tutorials

Introduction

An .htaccess file is used for an Apache web server as a way to configure the details of your website without altering the server configuration files. This file begins with a period to signify that it is hidden within the folder. An .htaccess file can be used to load customized error pages such as 404 pages, create URL redirects, implement password protected authentication for specific directories on your server, and more.

In this tutorial, you will learn how to enable, create, and use an .htaccess file, as well as some common uses and the impact on speed and security.

Key Takeaways

  • .htaccess is a per directory override file: Apache reads .htaccess files on each request to apply configuration for that directory and its subdirectories without changing the main server config.
  • AllowOverride must be enabled: Apache only honors .htaccess rules when the relevant <Directory> block sets AllowOverride to a non None value, such as AllowOverride All for the features you want to use.
  • Use .htaccess for shared hosting and limited access: On servers where you cannot edit the main Apache configuration, .htaccess gives site owners a way to manage redirects, mod_rewrite rules, authentication, and other directory specific behavior.
  • Modern Apache 2.4 uses Require instead of Allow or Deny: Older Allow from and Deny from directives have been replaced with Require syntax in Apache 2.4, so new configurations should rely on Require all granted and related directives.
  • Prefer main config when you can: On servers you control, Apache recommends placing permanent rules in the main configuration files for better performance and simpler debugging, and using .htaccess only when user level overrides are required.

Prerequisites

If you want to practice using an .htaccess file by following the examples throughout this tutorial, you will need:

  • One Ubuntu server set up with a non-root user with sudo privileges and firewall enabled. You can do this by following the Ubuntu initial server setup guide.

  • The Apache web server installed on your Ubuntu server. Learn how to set it up with our tutorial on How To Install the Apache Web Server on Ubuntu. Be sure to complete Step 5 and have a virtual host file for your domain. This tutorial will refer to your_domain as an example throughout and use /etc/apache2/sites-available/your_domain.conf for the virtual host file.

  • If you would like to practice with a domain (optional), you can set one up by purchasing a domain name on Namecheap, or use the domain registrar of your choice. You will also need both of the following DNS records set up for your server: two A records, one with your_domain and one with www.your_domain pointing to your server’s public IP address. Follow this introduction to DigitalOcean DNS for details on how to add them.

  • If you would also like to secure your virtual host, you can do so with a free trusted certificate, such as in our Let’s Encrypt guide for Apache. However, if you do not have a domain, you can use a self-signed certificate instead. This provides the same type of encryption, but without domain validation. Follow our self-signed SSL guide for Apache to set this up.

Once you’re done setting up, you can practice enabling and creating an .htaccess file in the next steps.

Enabling an .htaccess File

If you have access to the server settings you can edit the Apache configuration to allow the .htaccess file to override standard website configurations.

Begin by opening the apache2/sites-available/your_domain.conf virtual host file with your preferred text editor. Here, we’ll use nano:

  1. sudo nano /etc/apache2/sites-available/your_domain.conf

Assuming you followed Step 5 of the prerequisite Apache installation guide, this file will contain the following contents:

/etc/apache2/sites-available/your_domain.conf

    
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName your_domain
    ServerAlias www.your_domain
    DocumentRoot /var/www/your_domain
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Add the following Directory content block within the VirtualHost block to enable .htaccess usage:

/etc/apache2/sites-available/your_domain.conf


<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName your_domain
    ServerAlias www.your_domain
    DocumentRoot /var/www/your_domain
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /var/www/your_domain>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
                Require all granted
</Directory>
</VirtualHost>

The most important line of this Directory content block is the AllowOverride All, which enables the use of .htaccess files. The legacy Order and allow directives are kept here for compatibility, while the Require all granted line reflects the recommended Apache 2.4 syntax. After you’ve added this information, save and close the file. If you’re using nano you can do this by pressing CTRL + X then Y and ENTER.

Next, restart Apache:

sudo service apache2 restart

Now that your configuration settings have been updated to allow for the use of .htaccess files, in the next step you will create one.

Creating the .htaccess File

To create an .htaccess file in your terminal, you need to navigate to your web root directory. Your web root directory is where to place the .htaccess file so that your configurations can be properly executed for your website. The .htaccess file’s proper placement is important since configurations in that file affect everything in its directory and the directories after it. This means that if you’re serving a couple of different websites on the same Apache server, your .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. To create an .htaccess file for your website, run the following command:

sudo nano /var/www/your_domain/.htaccess

Now that you’ve learned a couple of ways to create an .htaccess file, next we’ll review some common uses of an .htaccess page.

Common Uses for an .htaccess Page

There are five common uses for an .htaccess page on your site:

Mod_Rewrite

One of the most useful facets of the .htaccess file is mod_rewrite. You can use the .htaccess file to designate and alter how URLs and web pages on your sites are displayed to your users. At a minimum, a rewrite configuration needs RewriteEngine On and one or more RewriteRule lines. Learn more about how you can do this with our tutorial on How To Set Up mod_rewrite.

Authentication

To set up security authentication with .htaccess, you can create a password file called .htpasswd to authenticate users. Making this change will create a password portal that prompts site visitors to enter a password if they want to access certain sections of the webpage. When creating this file, make sure to store it somewhere other than the web directory for security reasons.

To create the file, run the htpasswd command and include the -c option, and the username to create the specified htpasswd file. Once this happens, a prompt will ask you to provide a password. You can insert as many lines as needed into the htpasswd file, but be sure that every user gets their own respective line. The following example illustrates how to create a new entry in the file, in this case for the user sammy:

sudo htpasswd -c /etc/apache2/.htpasswd sammy

You can check the contents of this file by running cat /etc/apache2/.htpasswd, and it will output the username and encrypted password for each record you added.

Once you’ve added your desired user(s), next open up the .htaccess file. If you followed the prerequisites guide, this will be located in the following location:

sudo nano /var/www/your_domain/.htaccess

Keep in mind that in this example we’re restricting the entire document root based on /var/www/your_domain, but this can be placed in any directory to which you want to restrict access.

Once this file is open, add the following contents and save the changes to begin using the password function:

/var/www/your_domain/.htaccess

AuthType Basic
AuthName "Restricted Content"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user

To learn more, read our tutorial on How To Set Up Password Authentication with Apache.

Custom Error Pages

An .htaccess file additionally allows you to create custom error pages for your site. Some of the most common errors are:

  • 400 Bad Request
  • 401 Authorization Required
  • 403 Forbidden Page
  • 404 File not Found
  • 500 Internal Error

To make a page user-friendly and provide more information to the site visitor than the default server error page offers, you can use the .htaccess file to create custom error pages.

MIME Types

In cases where your site features some application files that your server was not set up to deliver, you can add Multipurpose Internet Mail Extensions (MIME) types to your Apache server in the .htaccess file with the following code:

/var/www/your_domain/.htaccess

AddType audio/mp4a-latm .m4a

Be sure to replace the application and file extension with the MIME type that you want to support. For this example, we specified an audio file MIME type.

SSI

Server side includes (SSI) are a great time-saver on a website. One of the most common uses of SSI is to update a large number of pages with some specific data without having to update each page individually. For example, if you want to change a quotation at the bottom of a page.

To enable SSI, insert the following code into your .htaccess file:

/var/www/your_domain/.htaccess

AddType text/html .shtml
AddHandler server-parsed .shtml</pre>

These lines tell the .htaccess that .shtml files are valid, with the second line specifically making the server parse all files ending in .shtml for any SSI commands.

However, if you have many .html pages that you are not eager to rename with .shtml extensions, you can use another tactic to parse them for SSI commands, the XBitHack.

You can use this XBitHack tactic by adding the following line to the .htaccess file to make Apache check all the .html files with the appropriate permissions for SSI:

/var/www/your_domain/.htaccess

XBitHack on

To make a page eligible for the XBitHack, use the chmod command to change permissions:

chmod +x pagename.html

Now that you have an understanding of a few common uses for an .htaccess page, next you will learn more about the impact an .htaccess file has on speed and security, and how to troubleshoot common errors.

Speed and security with .htaccess files

Even though an .htaccess file can be used to improve a site, there are two things to be aware of that it can influence: speed and security.

Regarding speed, the .htaccess file may slow down your server, but for most servers, this will probably be an imperceptible change. This could be because of the location of the page since the .htaccess file affects the pages in its directory and all of the directories after it. This means that each time a page loads, the server scans its directory, and any directories preceding it until it reaches the highest directory or an .htaccess file. This process will occur as long as the AllowOverride directive allows the use of .htaccess files.

For security, the .htaccess file is much more accessible than standard Apache configuration and the changes are made live instantly (without the need to restart the server). This grants users permission to make alterations in the .htaccess file, giving them a lot of control over the server itself. Any directive placed in the .htaccess file, has the same effect as it would in the Apache configuration itself. It’s also important to note that Apache generally discourages the use of .htaccess if the user can access the Apache configuration files themselves.

On servers you manage directly, a good pattern is to place permanent rules in the main Apache configuration and reserve .htaccess files for cases where site level administrators need to manage their own settings without reloading the web server.

Troubleshooting common .htaccess errors

Because .htaccess files are parsed on every request, a small syntax mistake can cause visible errors on your site. Here are some common issues and how to investigate them.

1. 500 Internal Server Error after editing .htaccess

If you see a 500 Internal Server Error immediately after adding or changing .htaccess rules, Apache may be rejecting the file due to invalid syntax or a disabled module.

  • Check the Apache error log for details:
sudo tail -n 50 /var/log/apache2/error.log
  • Look for messages that reference .htaccess, RewriteRule, or unknown directives.
  • Confirm that mod_rewrite or other referenced modules are enabled with sudo a2enmod rewrite followed by sudo systemctl reload apache2.
  • If you are unsure which line caused the problem, temporarily comment out new rules and add them back one at a time.

2. .htaccess rules are ignored completely

If your .htaccess changes appear to be ignored, the most common reason is that AllowOverride is not set to permit the directives you are using.

  • Confirm that your <Directory> block for the site contains AllowOverride All or a value that includes the correct override scope.
  • Make sure the .htaccess file is in the directory Apache is serving from. For Ubuntu based Apache installations with name based virtual hosts this is usually /var/www/your_domain.
  • Check file permissions to ensure Apache can read the file, for example with sudo ls -l /var/www/your_domain/.htaccess.

3. Redirect loops and unexpected rewrite behavior

Complex rewrite rules can easily cause redirect loops or unexpected status codes if test conditions do not match as expected.

  • Start with simple Redirect directives before moving to RewriteRule if you only need basic path or host redirects.
  • When you do use mod_rewrite, start with a single rule and test its behavior in a restricted environment before applying it to the full site.
  • Use your browser’s network inspector or tools like curl -I to see response codes and Location headers when debugging redirect chains.

FAQs

1. What is the .htaccess file used for?

The .htaccess file is a per directory configuration file that Apache reads on each request to adjust behavior for that directory and its subdirectories. You can use it for tasks such as URL rewrites, redirects, access control, authentication, and custom error pages when you do not want or cannot edit the main Apache configuration files.

2. Where is the .htaccess file located?

Apache looks for .htaccess in each directory that is covered by a <Directory> or <Location> block with AllowOverride enabled. On Ubuntu based Apache servers configured with name based virtual hosts, you typically place the file in the document root such as /var/www/your_domain. On shared hosting, the file is commonly located in the public_html directory for your site.

3. Why is my .htaccess file not working?

If your .htaccess file does not seem to have any effect, it is often because AllowOverride is set to None for that directory, or because the file is not in the directory Apache is actually serving from. Confirm the <Directory> path in your virtual host configuration, check that AllowOverride allows the directives you are using, and verify that the file is readable by the web server user. Reviewing the Apache error log can also help you spot syntax issues.

4. Does .htaccess affect performance?

Yes, .htaccess can affect performance, because Apache must check for .htaccess files in each directory along the path on every request when AllowOverride is enabled. On most sites this overhead is small, but on high traffic servers or complex directory structures the extra file system checks can add up. When you control the server configuration, Apache recommends moving permanent rules into the main configuration to avoid this cost.

5. Can I use .htaccess without Apache?

The .htaccess mechanism is specific to Apache HTTP Server and is not processed by other web servers such as Nginx or Caddy. Those servers have their own configuration formats for per site or per location rules. If you migrate a site from Apache to another web server, you will need to translate relevant .htaccess directives into that server’s native configuration.

Conclusion

The .htaccess file gives you a lot of flexibility to build up your site. To learn more about securing your site, read our tutorial on setting up password authentication with Apache. You can also read more in our tutorial about installing an Apache web server and specifically important Apache Files and Directories.

If you are configuring Apache on newer Ubuntu releases or building dynamic applications with PHP, you may also find these tutorials helpful:

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.