Htaccess Tutorial and Tester
.htaccess is a file used by an Apache webserver to manage access.
.htaccess tester
.htaccess variables
The strength of using .htaccess is that it gives you many variables you can use to create your own customized behavior.
Assuming your URL is https://domain1.com/test.php?user=joe, here are the most common ones, assuming your :
- %{DOCUMENT_ROOT}
This is the root folder of your website.
Usually something like /var/www/domain1.com. - %{HTTP_COOKIE}
Check cookies associated with request.
RewriteCond %{HTTP_COOKIE} ^.*darkmode=on.*$RewriteRule ^(.*)$ /$1?darkmode=true [NE,L]
- %{HTTP_FORWARDED}
Tells you if the client is using a proxy. - %{HTTP_HOST}
The hostname fragment of the URL.
In our example domain1.com. - %{HTTP_REFERER}
The web page that sent this request. - %{HTTP_USER_AGENT}
The useragent of the device requesting the URL.
Useful to identify mobile devices or bots and scrapers. - %{HTTPS}
Check if HTTPS is enabled. - %{QUERY_STRING
The query fragment of the URL.
In our example user=joe. - %{REQUEST_FILENAME}
The full file path requested
In our example /var/www/domain1.com/public_html/test.php. - %{REQUEST_METHOD
The method of the request (GET,POST,PUT,DELETE).
Useful if you you are serving an API. - %{REQUEST_URI}
The requested path relative to the domain.
In our example /test.php. - %{SERVER_ADDR}
The IP address of the server receiving the request.
Useful if you have multiple servers and need to debug. - %{SERVER_NAME}
The domain name of the server receiving the request.
Useful if you have multiple servers and need to debug.
.htaccess flags
Flags are used to provide additional customization for your rules. Here are the most common ones:
- F → Forbidden (403 header)
- G → Gone - no longer exists
- L → Last - stop processing rules
- NC → Case insensitive
- NE → Do not escape output
- P → Proxy
- R[=code] → Redirect to new URL, with optional code
- QSA → Append query string
- OR → Combine with next rule using 'OR' instead of the default of 'AND'
.htaccess Rewrite and Redirection Rules
The most common use case for .htaccess is to handle URL rewrites and redirecting to different pages.
Remember you need to set RewriteEngine on as very first line.
Serve All Requests With One PHP File with .htaccess
RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^([^?]*)$ /index.php [NC,L,QSA]
Force www with .htaccess
RewriteCond %{HTTP_HOST} ^example\.com [NC]RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
Force HTTPS with .htaccess
RewriteCond %{HTTPS} !onRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Remove Trailing Slash with .htaccess
RewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)/$ /$1 [R=301,L]
Redirect a Single Page with .htaccess
Redirect 301 /oldpage.html https://www.yoursite.com/newpage.html
Redirect an Entire Site with .htaccess
Redirect 301 / https://newsite.com/
.htaccess for Security
Your .htaccess file can also be used to implement security features.
Deny Bot access with .htaccess
RewriteCond %{HTTP_USER_AGENT} ^\-?$ [OR]RewriteCond %{HTTP_USER_AGENT} ^.*(<|>|'|%0A|%0D|%27|%3C|%3E|%00).* [NC,OR]RewriteCond %{HTTP_USER_AGENT} ^.*(HTTrack|clshttp|archiver|loader|email|nikto|miner|python).* [NC,OR]RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|libwww\-perl|curl|wget|harvest|scan|grab|extract).* [NC]RewriteRule ^(.*)$ - [F,L]
Deny Access to Hidden Files and Directories with .htaccess
RewriteCond %{SCRIPT_FILENAME} -d [OR]RewriteCond %{SCRIPT_FILENAME} -fRewriteRule "(^|/)\." - [F]
Disable Directory Browsing with .htaccess
Options All -Indexes
Disable Image Hotlinking with .htaccess
RewriteCond %{HTTP_REFERER} !^$RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]RewriteRule \.(jpg|jpeg|png|gif|webp|bmp)$ - [NC,F,L]
.htaccess for Performance
Your .htaccess file can also be used to implement performance features.
Compress files with .htaccess
<IfModule mod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file \.(html?|txt|css|log|js|php|pl)$ mod_gzip_item_include handler ^cgi-script$ mod_gzip_item_include mime ^text/.* mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_item_exclude mime ^image/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*</IfModule>
Set cache expiration policy with .htaccess
<IfModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 7 days" # Images ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/webp "access plus 1 year" ExpiresByType image/svg+xml "access plus 1 year" ExpiresByType image/x-icon "access plus 1 year" # Video ExpiresByType video/webm "access plus 1 year" ExpiresByType video/mp4 "access plus 1 year" ExpiresByType video/mpeg "access plus 1 year" # Fonts ExpiresByType font/ttf "access plus 1 year" ExpiresByType font/otf "access plus 1 year" ExpiresByType font/woff "access plus 1 year" ExpiresByType font/woff2 "access plus 1 year" ExpiresByType application/font-woff "access plus 1 year" # CSS, JavaScript ExpiresByType text/css "access plus 1 month" ExpiresByType text/javascript "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" # Others ExpiresByType application/pdf "access plus 1 month" ExpiresByType image/vnd.microsoft.icon "access plus 1 year"</IfModule>
Limit Upload File Size with .htaccess
LimitRequestBody 1048576
Miscellaneous .htaccess directives
Finally, some additional directives you can use to further customize your server.
Custom Error Pages with .htaccess
ErrorDocument 500 "Houston, we have a problem."ErrorDocument 401 https://error.yourdomain.com/mordor.htmlErrorDocument 404 /errors/halflife3.html
Force Downloading with .htaccess
<Files *.zip> ForceType application/octet-stream Header set Content-Disposition attachment</Files>
Hide Server Info (Server Signature) with .htaccess
ServerSignature Off
Set Server Timezone with .htaccess
SetEnv TZ America/Los_Angeles
Multisite .htaccess
If you're using Apache with multiple virtualhosts (ie one server hosting multiple domains), you might have wondered how to use a single htaccess file.
This is can easily be done by placing the htaccess file in the parent folder instead of the usual domain root folder.
For example, if your different website files are stored in /var/www/domain1.com/public_html, /var/www/domain2.com/public_html etc, rather than having an htaccess file in every public_html folder you can simply create a "master" htaccess file and place it in /var/www/.
Just remember you will now need to account for a different root.
For example this:
Redirect 301 /oldpage.html https://www.yoursite.com/newpage.html
will need to written as:
Redirect 301 /domain1.com/public_html/oldpage.html https://www.domain1.com/newpage.html