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’s 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.
If you want to practice using an .htaccess
file by following the examples throughout this tutorial, you will need:
One Ubuntu 20.04 server set up with a non-root user with sudo
privileges and firewall enabled. You can do this by following the Ubuntu 20.04 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 20.04. 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, get one free on Freenom, 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.
.htaccess
FileIf 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
:
Assuming you followed Step 5 of the prerequisite Apache installation guide, this file will contain the following contents:
<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:
<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
</Directory>
</VirtualHost>
The most important line of this Directory
content block is the AllowOverride All
, which enables the use of .htaccess
files. 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:
Now that your configuration settings have been updated to allow for the use of .htaccess
files, in the next step you will create one.
.htaccess
FileTo 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:
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.
.htaccess
PageThere are five common uses for an .htaccess
page on your site:
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. Learn more about how you can do this with our tutorial on How To Set Up mod_rewrite
.
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:
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:
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:
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.
An .htaccess
file additionally allows you to create custom error pages for your site. Some of the most common errors are:
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. Read more in our tutorial on How to Configure Apache to Use Custom Error Pages.
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:
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.
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:
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:
XBitHack on
To make a page eligible for the XBitHack
, use the chmod
command to change permissions:
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.
.htaccess
FilesEven 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 as was demonstrated in the enabling an .htaccess
file step; whether or not the .htaccess
files actually exist.
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.
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
I followed the tutorial but when i upload via filezilla (Alreay installed proftpd), it says 550 .htaccess: Permission denied
Are you upload to other files to that directory as that user or is only .htaccess prevented from being uploaded?
I am uploading to var/www/ directory via filezilla, and filezilla wont allow me to upload .htaccess
Can you upload any other files that aren’t .htaccess, such as “test-file”?
403 forbidden site after doing this ,
i have to change AllowOverride All
to
AllowOverride None
and its working again
Hi everybody, I have same and fixed this problems.
admin, what do you mean by, “Paste your htaccess code”? paste what, where? thanks.
@artisannm: Your htaccess code is the code you came up with after following this article.
Hmm, nothing is helping. I am trying to install a community forum program called Elgg. its located in the top directory. I’m using filezilla for my ftp. The installer has a precheck: “PHP Your server’s PHP satisfies all of Elgg’s requirements.”
"Web server We think your server is running the Apache web server.
The rewrite test failed and the most likely cause is that AllowOverride is not set to All for Elgg’s directory. This prevents Apache from processing the .htaccess file which contains the rewrite rules.
A less likely cause is Apache is configured with an alias for your Elgg directory and you need to set the RewriteBase in your .htaccess. There are further instructions in the .htaccess file in your Elgg directory."
I can’t edit the .htaccess permissions inside the Elgg directory. I have changed Allow Override to All. I followed Admin’s steps to no avail. I didn’t follow the steps for creating custom urls etc, as that wasn’t applicable.
I did check inside the Elgg folder and copied the .htaccess-dist file over to the .htaccess and still can’t change permissions on .htaccess but can change permissions on .htaccess-dist
I also tried uncommenting Rewrite Base in .htaccess I have restarted apache2 as guided. I can’t get past this .htaccess file in order to continue setting up the Elgg install. I’m on ubuntu 12.04, interfacing through Terminal on an imac. I have mysql up and running along with apache2. I have a phpbb3 forum up and running as well, from the top directory along with a website.
thanks for your help in advance…
@artisannm: Please pastebin apache’s config files (and .htaccess).
Try enabling the rewrite module: <pre>sudo a2enmod rewrite sudo service apache2 restart</pre>
I had the same problem. Thanks to post my admin I got it working. His comment should be included in the main article.
“1. Install Mod_rewite sudo a2enmod rewrite”
Admin Thank you!
Hi, I’ve got some problem with htaccess in a virtualhost on Ubuntu 12.04. First of all in my “/etc/apache2/sites-available/” folder there is 000-default.conf and not default.conf but this was not the problem. Sudo a2enmod rewrite return Module rewrite already enabled and in the site.conf where I need to use htaccess, AllowOverride was set correctly to All but it didn’t work because in my /ect/apache2/apache2.conf I had AllowOverride None.
Hope this help
Well, as said on tutorial, all htaccess do apache config can do as well too. is there any tutorial teaching this?
Thanks a lot!!!
AuthName Please Enter Password Should be: AuthName “Please Enter Password”
As per the Apache documentation: http://httpd.apache.org/docs/current/mod/mod_authn_core.html#authname
guys… I think this is for ubuntu OS. Pls guide me to set up on Centos
@team: Everything should be the same on CentOS except for the paths – you have to edit <code>/etc/httpd/conf/httpd.conf</code> instead.
you wrote about activating .htaccess, what about DEACTIVATE it? I don’t want to use it any longer (it came enable by default, and I want to disable it). How can i do this? Thanx.
Once I write:
sudo nano /etc/apache2/sites-available/default
The file is empty! Is there another code for me to see the info? Thanx.
Hello,
The new location of the default config file is:
Regards, Bobby
@pauli
On more recent versions of Ubuntu the default conf file is named:
/etc/apache2/sites-available/000-default.conf
To disable the .htaccess file, find the part of your apache conf that looks like:
And change “AllowOverride All” to “AllowOverride None”
I try the auth code like this
AuthType Basic AuthName Admin area only AuthGroupFile /dev/null AuthUserFile /var/www/knigoobzor.ru/public_html/admin/.htpasswd Require valid-user
But when I reach knigoobzor.ru/admin in browser I get "Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request…"
What’s wrong? The paths seem to be correct.
As of now “/etc/apache2/sites-available/default” is not working. The correct one would be “sudo nano /etc/apache2/apache2.conf”
good Tutorials man giving me ideas about my project But guys i have the problem with my apache users they can’t read freeradius log file on centos 6.5 , do i have to give them permission through htaccess file ? if how i tried and not fix anyone please help me out
Logged in just to say THANKS to @matteo.poile your solution did the trick!
Hello,
Why is the sudo nano /etc/apache2/sites-available/default load blank page?, i cannot find any line of like : <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory>
Thank you
If you can’t find it in /etc/apache2/sites-available/default it’s in /etc/apache2/apache2.conf
Change it to below:
<Directory /var/www/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>
Make sure to turn mod rewrite on: a2enmod rewrite and restart: service apache2 restart
If you also rewriting links: http://alexcican.com/post/how-to-remove-php-html-htm-extensions-with-htaccess/
Hello, I have multiple websites in my server, does I have to edit the file and add the path for each one? Something like this:
I made it as u say, but I got an error in my main website, the others are working. Says 500 error.
Thanks
I have 3 site on my server, AFAIK, per site, you need to add virtual host block on 000-default.conf add directory block on apache2.conf then service apache2 restart
if you put .htpasswd outside, you need to make it accessible by www-data ( correct me if i’m wrong ) with CHOWN -R www-data:www-data /path/to/passwd
Broken link: http://cs.its.uiowa.edu/wts/htpasswd.shtml
Thanks! I’ve updated the link.
Thanks for sharing this informative article. I would like to add few more things that we can do using htaccess file -
Source: http://catchupdates.com/what-is-htaccess-file/
Hi,
I am getting the following error, please help. It appears on /wp-admin
…
’ . __( ‘Welcome to your WordPress Dashboard! This is the screen you will see when you log in to your site, and gives you access to all the site management features of WordPress. You can get help for any screen by clicking the Help tab in the upper corner.’ ) . ’
'; // Not using chaining here, so as to be parseable by PHP4. $screen = get_current_screen(); $screen->add_help_tab( array( ‘id’ => ‘overview’, ‘title’ => __( ‘Overview’ ), ‘content’ => $help, ) ); // Help tabs $help = ’
’ . __( ‘The left-hand navigation menu provides links to all of the WordPress administration screens, with submenu items displayed on hover. You can minimize this menu to a narrow icon strip by clicking on the Collapse Menu arrow at the bottom.’ ) . ’ '; $help .= ’
’ . __( ‘Links in the Toolbar at the top of the screen connect your dashboard and the front end of your site, and provide access to your profile and helpful WordPress information.’ ) . ’ '; $screen->add_help_tab( array( ‘id’ => ‘help-navigation’, ‘title’ => __( ‘Navigation’ ), ‘content’ => $help, ) ); $help = ’
’ . __( ‘You can use the following controls to arrange your Dashboard screen to suit your workflow. This is true on most other administration screens as well.’ ) . ’ '; $help .= ’
…
Thanks for this great tutorial. I encountered a few issues when trying to get this to work on Debian 8.2 and Apache 2.4.10: there was no default.conf and editing the 000-default.conf did not work.
I had to edit /etc/apache2/apache2.conf, and ensured the following part looked like this:
<Directory /var/www/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>
(AllowOverride All is the entry that made .htaccess work)
Landorin You just saved me so much time! I am a super novice and there’s so much information on the web that is complex and confounding and with one little post you helped me immensely. I have literally wasted HOURS of time trying to figure this out. The apache2.conf file was it.
If anyone else stumbles upon this while trying to set up a mediawiki application here are two things that are super helpful:
I wish I could give you a hug you’re awesome!
Not exactly sure why this was my case but my <Directory /var/www/> directive in my apache2.conf file had to look like this before URL rewrite would function properly:
Where most people were able to get it to work without the “Require all granted” line, mine would not. Does enabling this line cause any security vulnerabilities I should be aware of?
I usually get these errors on WordPress but I just built a site from scratch and I got this error. Thanks for sharing this post.
This does not apply to Apache 2.4 Part 1) The filename is now called 000-default.conf that you must edit. see: https://httpd.apache.org/docs/trunk/upgrading.html to achieve the above results you will use:
ServerAdmin webmaster@localhost DocumentRoot /var/www <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>
Part 2) .htpasswd see: https://httpd.apache.org/docs/trunk/programs/htpasswd.html There are some changes there too.
73s Have a good day
Hello, I followed the guide for 2. Authentication and tested the combination for “jsmith”. But it didn’t work. The “site” I’ve tested is a little CGI (Perl) project under a local Webserver installation on a Windows system with XAMPP. But the webserver should work as well. If I ommit the .htaccess all works fine. The .htpasswd file is placed well and is found by the webserver. Thanks in advance, regards, Thomas
Solved as for me: in XAMPP there is - just like under Linux/Apache webserver - a command htpasswd. This command did create a much more longer line as I did with the normal crypt (with salt). Also XAMPP (for Windows) does - it seems so - require the .htpasswd file with Windows line endings. I did use Linux line endings before. Copying the so generated line from the created .htpasswd to the existing .htpasswd and converting the file to Unix line endings did solve the problem.
As an added note when modifying the apache host configuration,
AllowOverride All
may have to be set in multiple config files. (e.g.000-default.conf
,default-ssl.conf
, etc.)The port may differ depending on if using SSL/TLS or not. (e.g.
<VirtualHost _default_:443>
,<VirtualHost *:80>
, etc.)Thanks for the helpful article but for my RHEL 7 + Apache 2.4, htaccesstools’ generator worked while the one linked in the article was broken and ended up in the server accepting all strings as valid.
Under Apache 2.4 (which is installed by default under Debian 10 and probably other operating systems at this point), the advice above is not quite right.
My particular application was to add password control to some directories. I had to edit the config in
/etc/apache2/apache2.conf
to containAnd then add
.htaccess
files to the necessary directories, each containing.htpasswd was created with
htpasswd /etc/apache2/.htpasswd
and then of course reboot Apache with
sudo service apache2 restart
As most have seen and commented, in order to make .htaccess file work, you’ll need to add the following to the
apache2.conf
:Explanation of Each Directive
<Directory /var/www/>
…</Directory>
:/var/www/
directory and all its subdirectories.Options Indexes FollowSymLinks MultiViews
:This directive controls which server features are available in the specified directory.
Indexes
:index.html
), Apache will generate and display a directory listing. This can be a security risk if not used carefully, as it exposes the directory contents to the web.FollowSymLinks
:/var/www/
pointing to another file or directory, Apache will follow it.MultiViews
:AllowOverride All
:.htaccess
files (if present in the directory) can override server configuration.All
means that all types of directives are allowed to be overridden by.htaccess
files. This can be useful for allowing directory-specific configurations but can also pose a security risk if not managed properly, as it allows users to modify server behavior within their directories.Require all granted
:Require all granted
means that all requests are allowed access. This effectively means anyone can access the content served from/var/www/
. This setting is essential for publicly accessible web content but should be used cautiously, especially for directories containing sensitive data.Summary
By adding this block to your
apache2.conf
, you’re configuring Apache to:/var/www/
..htaccess
files in/var/www/
to override server configurations./var/www/
without restrictions.