.htaccess is a simple text file that lets you control how your web server handles requests. While it was originally designed for managing access to directories, it now serves many other purposes.
This guide isn’t a deep dive into .htaccess but rather a practical introduction with a collection of useful code snippets. While .htaccess is powerful, that doesn’t mean you should use it for everything. Understanding when and how to apply it can improve your website’s security, performance, and functionality.
What Is .htaccess?
The .htaccess file, short for “hypertext access”, is a configuration file primarily used on Apache servers. It allows users to control access permissions, password-protect directories, set up redirects, customize error pages, and block specific IP addresses.
Paired with an .htpasswd file, it enables granular directory access control for multiple users. Many hosting providers support .htaccess, but it’s not universal—some web servers, like Nginx, use different methods.
Where to Find Your .htaccess File?
By default, the .htaccess file is hidden in cPanel’s File Manager and other hosting control panels. You can reveal it by enabling the “Show Hidden Files” option in your file manager settings.
If you can’t find the file, don’t panic – it might not exist yet. In most cases, it should be in your website’s root directory, typically named public_html or www. If you manage multiple websites under the same hosting account, each site may have its own .htaccess file within its respective folder.
Most system files that start with a period (.) are hidden. If your .htaccess file isn’t visible, check your hosting settings or manually create one in a text editor.
.htaccess Cheat Sheet & Code Samples
While .htaccess can do a lot, knowing the right commands is key. To make things easier, we’ve compiled a cheat sheet with the most commonly used .htaccess rules. Whether you need to block bad bots, force HTTPS, customize error pages, or improve SEO, you’ll find ready-to-use code snippets below.
Simply copy, paste, and tweak them to fit your needs. Let’s dive in!
Note: Please double-check and verify any rules before using them. We are not responsible for any issues that may arise – use them at your own risk. Also, most rules require the RewriteEngine On directive in your .htaccess file to function properly.
Rewrite and Redirection Rules
Serve All Requests With One PHP File with .htaccess
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*)$ /index.php [NC,L,QSA]
WordPress .htaccess for permalinks with .htaccess
(This is the only rule in this section that includes the RewriteEngine on rule.)
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
Force www with .htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
Force www in a Generic Way with .htaccess
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Force non-www with .htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
Force non-www in a Generic Way with .htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]
Force HTTPS with .htaccess
Use this to redirect non HTTPS requests to a HTTPS request. I.e. if you go to https://example.com/ it will redirect to https://example.com.
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Force HTTPS Behind a Proxy with .htaccess
Useful if you have a proxy in front of your server performing TLS termination.
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Force Trailing Slash with .htaccess
Use the follow .htaccess rule to redirect any urls to the same url (but with a trailing slash) for any requests that do not end with a trailing slash. I.e. redirect from https://example.com/your-page to https://example.com/your-page/
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
Remove Trailing Slash with .htaccess
Use this to remove any trailing slash (it will 301 redirect to the non trailing slash url)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]
Redirect a Single Page with .htaccess
Redirect a single URL to a new location
Redirect 301 /oldpage.html https://www.yoursite.com/newpage.html
Redirect 301 /oldpage2.html https://www.yoursite.com/folder/
Alias a Single Directory with .htaccess
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1
Alias Paths To Script with .htaccess
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]
This example has an index.fcgi file in some directory, and any requests within that directory that fail to resolve a filename/directory will be sent to the index.fcgi script. It’s good if you want baz.foo/some/cool/path to be handled by baz.foo/index.fcgi (which also supports requests to baz.foo) while maintaining baz.foo/css/style.css and the like.
Redirect an Entire Site with .htaccess
Use the following .htaccess rule to redirect an entire site to a new location/domain
Redirect 301 / https://newsite.com/
This way does it with links intact. That is www.oldsite.com/some/crazy/link.html will become www.newsite.com/some/crazy/link.html. This is extremely helpful when you are just “moving” a site to a new domain.
Alias “Clean” URLs with .htaccess
This snippet lets you use “clean URLs” — those without a PHP extension, e.g. example.com/users instead of example.com/users.php.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]
Security Rules
Deny All Access with .htaccess
If you want to prevent apache serving any files at all, use the following.
This will stop you from accessing your website. If you want to deny all access but still be able to view it yourself please read the next rule:
Deny from all
Deny All Access Except Yours (Only allow certain IPs) with .htaccess
Use this to only allow certain IP addresses to access your website.
# Require all denied
# Require ip xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx is your IP. If you replace the last three digits with 0/12 for example, this will specify a range of IPs within the same network, thus saving you the trouble to list all allowed IPs separately.
Please see the next rule for the ‘opposite’ of this rule!
Block IP Address with .htaccess
This will allow access to all IPs except the ones listed. You can use this to allow all access Except Spammer’s IP addresses.
Replace xxx.xxx.xxx.xxx and xxx.xxx.xxx.xxy with the IP addresses you want to block.
Apache 2.4
# Require all granted
# Require not ip xxx.xxx.xxx.xxx
# Require not ip xxx.xxx.xxx.xxy
Allow access only from LAN with .htaccess
order deny,allow
deny from all
allow from 192.168.0.0/24
Deny Access To Certain User Agents (bots) with .htaccess
Use this .htaccess rule to block/ban certain user agents
RewriteCond %{HTTP_USER_AGENT} ^User\ Agent\ 1 [OR]
RewriteCond %{HTTP_USER_AGENT} ^Another\ Bot\ You\ Want\ To\ Block [OR]
RewriteCond %{HTTP_USER_AGENT} ^Another\ UA
RewriteRule ^.* - [F,L]
Deny Access to Hidden Files and Directories with .htaccess
Hidden files and directories (those whose names start with a dot .) should most, if not all, of the time be secured. For example: .htaccess, .htpasswd, .git, .hg.
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]
Alternatively, you can just raise a Not Found error, giving the attacker dude no clue:
RedirectMatch 404 /\..*$
Deny Access To Certain Files with .htaccess
Use this to block or deny access to certain files
<files your-file-name.txt>
order allow,deny
deny from all
</files>
Deny Access to Backup and Source Files with .htaccess
These files may be left by some text/html editors (like Vi/Vim) and pose a great security danger, when anyone can access them.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
## Apache 2.2
Order allow,deny
Deny from all
Satisfy All
## Apache 2.4
# Require all denied
</FilesMatch>
Disable Directory Browsing with .htaccess
Options All -Indexes
Enable Directory Listings with .htaccess
Options All +Indexes
Disable Listing Of Certain Filetypes with .htaccess
Use this to exclude certain file types from being listed in Apache directory listing. You could use this to stop .pdf files, or video files showing up.
IndexIgnore *.zip *.mp4 *.pdf
Disable Image Hotlinking with .htaccess
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
Redirect hotlinkers and show a different image with .htaccess
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?your-website.com/.*$ [NC]
RewriteRule \.(gif|jpg|png)$ https://www.your-website.com/do-not-hotlink-our-content.jpg [R,L]
Deny Access from certain referrers with .htaccess
Use this rule to block access to requests that include a referrer from a certain domain.
RewriteCond %{HTTP_REFERER} block-this-referer\.com [NC,OR]
RewriteCond %{HTTP_REFERER} and-block-traffic-that-this-site-sends\.com [NC]
RewriteRule .* - [F]
Password Protect a Directory with .htaccess
First you need to create a .htpasswd file somewhere in the system. Run the following command at the command line:
htpasswd -c /home/hidden/directory/here/.htpasswd the_username
Then you can use it for authentication. In your .htaccess file you need something like the following code, but make sure the AuthUserFile is the file path to the .htpasswd you just created. You should keep the .htpasswd in a directory not accesible via the web. So don’t put it in your /public_html/ or /www/ directory.
AuthType Basic
AuthName "Password Protected Dir Title"
AuthUserFile /home/hidden/directory/here/.htpasswd
Require valid-user
Password Protect a File or Several Files with .htaccess
AuthName "Password Protected Directory Title"
AuthType Basic
AuthUserFile /home/hidden/directory/here/.htpasswd
<Files "/a-private-file.txt">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>
Performance Rules
Compress Text Files with .htaccess
<IfModule mod_deflate.c>
# Force compression for mangled headers.
# https://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
</IfModule>
</IfModule>
# Compress all output labeled with one of the following MIME-types
# (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
# and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines
# as `AddOutputFilterByType` is still in the core directives).
<IfModule mod_filter.c>
AddOutputFilterByType DEFLATE application/atom+xml \
application/javascript \
application/json \
application/rss+xml \
application/vnd.ms-fontobject \
application/x-font-ttf \
application/x-web-app-manifest+json \
application/xhtml+xml \
application/xml \
font/opentype \
image/svg+xml \
image/x-icon \
text/css \
text/html \
text/plain \
text/x-component \
text/xml
</IfModule>
</IfModule>
Set Expires Headers with .htaccess
Expires headers tell the browser whether they should request a specific file from the server or just grab it from the cache. It is advisable to set static content’s expires headers to something far in the future.
If you don’t control versioning with filename-based cache busting, consider lowering the cache time for resources like CSS and JS to something like 1 week.
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault "access plus 1 month"
# CSS
ExpiresByType text/css "access plus 1 year"
# Data interchange
ExpiresByType application/json "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType text/xml "access plus 0 seconds"
# Favicon (cannot be renamed!)
ExpiresByType image/x-icon "access plus 1 week"
# HTML components (HTCs)
ExpiresByType text/x-component "access plus 1 month"
# HTML
ExpiresByType text/html "access plus 0 seconds"
# JavaScript
ExpiresByType application/javascript "access plus 1 year"
# Manifest files
ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds"
ExpiresByType text/cache-manifest "access plus 0 seconds"
# Media
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"
# Web feeds
ExpiresByType application/atom+xml "access plus 1 hour"
ExpiresByType application/rss+xml "access plus 1 hour"
# Web fonts
ExpiresByType application/font-woff2 "access plus 1 month"
ExpiresByType application/font-woff "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
ExpiresByType application/x-font-ttf "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
</IfModule>
Turn eTags Off with .htaccess
By removing the ETag header, you disable caches and browsers from being able to validate files, so they are forced to rely on your Cache-Control and Expires header.
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag None
Limit Upload File Size with .htaccess
Put the file size in bytes. . The code below limits it to 1mb.
LimitRequestBody 1048576
Miscellaneous Rules
Server Variables for mod_rewrite with .htaccess
%{API_VERSION}
%{DOCUMENT_ROOT}
%{HTTP_ACCEPT}
%{HTTP_COOKIE}
%{HTTP_FORWARDED}
%{HTTP_HOST}
%{HTTP_PROXY_CONNECTION}
%{HTTP_REFERER}
%{HTTP_USER_AGENT}
%{HTTPS}
%{IS_SUBREQ}
%{REQUEST_FILENAME}
%{REQUEST_URI}
%{SERVER_ADDR}
%{SERVER_ADMIN}
%{SERVER_NAME}
%{SERVER_PORT}
%{SERVER_PROTOCOL}
%{SERVER_SOFTWARE}
%{THE_REQUEST}
Set PHP Variables with .htaccess
php_value <key> <val>
For example:
php_value upload_max_filesize 50M
php_value max_execution_time 240
Custom Error Pages with .htaccess
ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 https://error.yourdomain.com/mordor.html
ErrorDocument 404 /errors/halflife3.html
Redirect users to a maintenance page while you update with .htaccess
This will redirect users to a maintenance page but allow access to your IP address. Change 555.555.555.555 to your IP, and YourMaintenancePageFilenameOrFullUrlUrl.html to your error page (or a whole URL, on a different domain).
ErrorDocument 403 YourMaintenancePageFilenameOrFullUrlUrl.html
Order deny,allow
Deny from all
Allow from 555.555.555.555
Force Downloading with .htaccess
Sometimes you want to force the browser to download some content instead of displaying it. The following snippet will help.
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
Disable Showing Server Info (Server Signature) with .htaccess
While many people consider this pointless (especially with regards to security), if you want to stop your server from giving away server info (the sever OS etc), use this:
ServerSignature Off
Prevent Downloading with .htaccess
Sometimes you want to force the browser to display some content instead of downloading it. The following snippet will help.
<FilesMatch "\.(tex|log|aux)$">
Header set Content-Type text/plain
</FilesMatch>
Allow Cross-Domain Fonts with .htaccess
CDN-served webfonts might not work in Firefox or IE due to CROS. The following snippet from alrra should make it happen.
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
Auto UTF-8 Encode with .htaccess
To have Apache automatically encode your content in UTF-8, use the following code. You can also swap the utf-8 for another character set if required:
# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8
# Force UTF-8 for a number of file formats
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml
Set Server Timezone (to UTC, or other time zone) with .htaccess
SetEnv TZ UTC
See a list of time zones . To set it to Los Angeles time zone:
SetEnv TZ America/Los_Angeles
Switch to Another PHP Version with .htaccess
If you’re on a shared host, chances are there are more than one version of PHP installed, and sometimes you want a specific version for your website. For example, requires PHP >= 5.4. The following snippet should switch the PHP version for you.
AddHandler application/x-httpd-php55 .php
Alternatively, you can use AddType
AddType application/x-httpd-php55 .php
Disable Internet Explorer Compatibility View
Compatibility View in IE may affect how some websites are displayed. The following snippet should force IE to use the Edge Rendering Engine and disable the Compatibility View.
<IfModule mod_headers.c>
BrowserMatch MSIE is-msie
Header set X-UA-Compatible IE=edge env=is-msie
</IfModule>
Execute PHP with a different file extension with .htaccess
The following code will run files ending in .ext with php:
AddType application/x-httpd-php .ext
Serve WebP Images Automatically If They Exist
If WebP images are supported and an image with a .webp extension and the same name is found at the same place as the jpg/png image that is going to be served, then the WebP image is served instead.
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
Setting up hosting can be confusing. That’s why we created HostScore Setup Help, a done-for-you service for getting your hosting configured the right way.
We help with SSL installation, DNS & nameserver setup, WordPress install or migration, and security tuning. One-time fee. Backed by a 100% refund guarantee.
Explore Our ServicesWrapping Up
The .htaccess file is a powerful tool, but it’s important to use it wisely. While it may be tempting to add extra rules for quick fixes, remember that .htaccess is not a primary configuration file.
Each time a server encounters a .htaccess file, it must read and execute it, overriding the main configuration settings. This process consumes resources and can slow down your website, especially if overused. Whenever possible, apply configurations directly at the server level (for instance., in Apache’s main config file) for better performance.
By using .htaccess efficiently and pairing it with a well-optimized hosting plan – you can enhance your website’s security, performance, and scalability
Frequent Asked Questions
Should I use .htaccess?
In a global usage sense the .htaccess file can offer a lot of convenience. However, this comes at a potentially high cost in server resources. Where possible, rely on mains server configuration rather than the .htaccess file.
How do I know if my .htaccess is working?
The simplest way to ensure your .htaccess file is working is to visit the URL of the directory that you’ve placed it in. If it is not working you will likely encounter a 500 Internal Server Error.
Can I have multiple .htaccess files?
.htaccess files can technically be placed in each directory that you want configured. If you run multiple websites, each home directory can have its own file – along with one in every subdirectory beneath it.
What is the rewrite rule in htaccess?
Rewrite is an Apache module that allows you to rewrite URL requests. It simply takes an incoming request and directs it towards one which you have specified to take its place instead.