.htaccess tools and directives

.htaccess, the file which control the Apache webserver, is very useful and allows you to do a lot of things.

The following tool can be used to test .htaccess rewrites:

The following tool can be used to test regular expressions:

Another rewrite rules tester:

1. PopUp authorization

<Directory “/var/www/html/”>
Order allow,deny
Allow from %allowed_ip(s)%
AuthName “Login Required”
AuthType Basic
AuthUserFile /var/www/apache_auth/.htpasswd
require valid-user
Satisfy any

Use the following command to create passwd file:

htpasswd -cmb /var/www/apache_auth/.htpasswd user password

2. Restricting access to defenite files in current folder:

<FilesMatch “.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$”>
Order Allow,Deny
Deny from all

3. Remove www in url
For some reasons, you might always remove (or use) the www prefix in your urls. The following snippet will remove the www from your website url and redirect any url with the www to the non-www version.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^your-site.com$ [NC]
RewriteRule ^(.*)$ http://your-site.com/$1 [L,R=301]

3.1. Force www in a generic way:

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|off
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

3.2. Force non-www:

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]

4. Prevent hotlinking
Hotlinking is a bad practice that consist of using the images from another site on yours. When you’re hotlinked by someone else, your bandwidth is used for someone else profit. Of course, you may want to prevent hotlinkers. Just add the following snippet to your .htaccess file after replacing the example urls by your own urls.

RewriteEngine On
#Replace ?mysite\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your “don’t hotlink” image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

5. Block wisitors, who came from definite domain

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} bannedurl1.com [NC,OR]
RewriteCond %{HTTP_REFERER} bannedurl2.com [NC,OR]
RewriteRule .* – [F]

6. Block requests from definite Browsers.
If you see some strange User-Agents in access logs (or on visitors report page) you can block that bad clients using .htaccess directives:

RewriteEngine On
RewriteBase /
SetEnvIfNoCase Referer “^$” bad_user
SetEnvIfNoCase User-Agent “^badbot1” bad_user
SetEnvIfNoCase User-Agent “^badbot2” bad_user
SetEnvIfNoCase User-Agent “^badbot3” bad_user
Deny from env=bad_user

7. Create custom error pages
Tired of the old errors pages of your site? Just create some html files with the look you want, upload them to your server, and add the following to your .htaccess file:

ErrorDocument 400 /errors/badrequest.html
ErrorDocument 401 /errors/badrequest.html
ErrorDocument 500 /errors/serverr.html

8. Force download of specific files
When offering some files such as mp3s, eps or xls, for download on your site, you may force download instead of letting the browser decide what to do.
This snippet will force the download of .xls and .eps files from your server.

<Files *.xls>
ForceType application/octet-stream
Header set Content-Disposition attachment
<Files *.eps>
ForceType application/octet-stream
Header set Content-Disposition attachment

9. Log PHP errors
This snippet is an interesting way to log errors from your php file into a log file. Just create a php_error.log file somewhere on your server, and add the snippet to your .htaccess file. Don’t forget to modify the log file location on line 7.

# display no errs to user
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log to file
php_flag log_errors on
php_value error_log /var/www/vhosts/%instance%/logs/php_error.log

10. Remove file extensions from urls
File extensions may be useful to developers, but there’s absolutely no need for your site visitors to be able to see them. This snippet will remove the .html extension on any html files. Of course, this code can be easily adapted to remove extensions from other file extensions such as php.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
# Replace html with your file extension, eg: php, htm, asp

11. Directory listing
On your web server, when a directory do not have an index file, Apache automatically create a list of all files from the current directory. If you do not wish that anyone can see which files are on your server, just add the following code to your .htaccess file to prevent automatic directory listing.

Options -Indexes

to enable it:

Options +Indexes

12. Reduce pages weight by compressing static data
Do you know that it is possible to send compressed data to the visitors, which will be decompressed by the client? This code will definitely save you (and your visitor) bandwidth and reduce your pages weight.

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml
text/javascript text/css application/x-javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4.0[678] no-gzip
BrowserMatch bMSIE !no-gzip !gzip-only-text/html

optional way to compress everything with gzip:

<IfModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file \.(html?|txt|css|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.*

13. Automatically add utf-8 char-set to files
In order to avoid encoding problems, you can force a specific encoding directly on your .htaccess file. That way, you’ll ensure that your html documents will always render correctly, even if your forget to add a directive on your html pages.

<FilesMatch “\.(htm|html|css|js)$”>
AddDefaultCharset UTF-8

14. Caching files on client side

<FilesMatch “.(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf)$”>
Header set Cache-Control “max-age=2592000”

max-age accespts value in seconds

15. Disable caching for definite files

<FilesMatch “.(pl|php|cgi|spl|scgi|fcgi)$”>
Header unset Cache-Control

16. Set Default index pages

DirectoryIndex mypage.html

17. Redirect everything to secure page

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

18. Simulate https behind the proxy:

There are multiple approaches here:
Using SetEnIF:

SetEnvIf X-Forwarded-Proto https HTTPS=on

Using mod_rewrite:

RewriteEngine on
RewriteCond %{X-Forwarded-Port} 443
RewriteRule .* – [E=HTTPS:on]

19. Set php variables:
General approach is the following:

php_value <key> <val>

For example:

php_value upload_max_filesize 50M
php_value max_execution_time 240

20.Force compression for mangled headers

<IfModule mod_deflate.c>
<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

21. Compress all output labeled with one of the following MIME-types

<IfModule mod_deflate.c>
<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 \

22. Redirect with multiple options of REQUEST_URI:

RewriteCond %{REQUEST_URI} ^/(uri1|uri2|uri3) [NC]
RewriteRule .* /new_uri/%{REQUEST_URI} [L]

Please note that in this case original REQUEST_URI will not change in the browser’s address bar.


Share Button

Leave a Reply

You must be logged in to post a comment.