.htaccess is a configuration file which is used on the web servers running the Apache Web Server. The .htaccess file is automatically loaded by the Web Server if there any and then the .htaccess file is executed by the Web Server. The .htaccess files can be used to change the configuration of the Web Server to add some additional functionality or remove some irrelevant features of the Apache Web Server.
Why use .htaccess file on your server
There are many advantages of using .htaccess on your server. They are listed below:
- .htaccess is just a single file which is placed on the root of your server or on the specific directory of the server you want.
- .htaccess file overwrites the server functionalities with respect to the functions you specify in this file. So it doesn’t need you to change the core scripts of your server.
- If any problem occurs with your .htaccess file which makes your server faulty then you can remove the .htaccess file and everything will be fine.
- You can define custom error pages. You can also password protect you directories or prevent image hot link and many more.
.htaccess Code Snippets
In this post I am sharing some very common .htaccess code snippets which will be helpful for your future server configuration. These .htaccess code snippets need to be modified as of your case because some values will not match your configuration.
01. Prevent Hotlinking Images
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]
02. Blacklist Undesired Users And Bots Ip Address
<Limit GET POST PUT> order allow,deny allow from all deny from 123.456.789 deny from 93.121.788 deny from 223.956.789 deny from 128.456.780 </limit>
03. Redirect Hotlinkers
RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http://(subdomain\.)?domain.tld/.*$ [NC] RewriteRule ^.*\.(bmp|tif|gif|jpg|jpeg|jpe|png)$ http://google.com [R]
04. Configure Your Website For HTML5 Videos
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !=/favicon.ico AddType video/ogg .ogv AddType video/ogg .ogg AddType video/mp4 .mp4 AddType video/webm .webm AddType application/x-shockwave-flash swf
05. Use Browser Caching To Improve Blog Speed
<IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType text/css "access 1 month" ExpiresByType application/pdf "access 1 month" ExpiresByType text/x-javascript "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 2 days" </IfModule>
06. Force Trailing Slash
<IfModule mod_rewrite.c> RewriteCond %{REQUEST_URI} /+[^\.]+$ RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L] </IfModule>
07. Remove File Extensions From Urls
RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.html -f RewriteRule ^(.*)$ $1.html # Replace html with your file extension, eg: php, htm, asp Source: http://eisabainyo.net/weblog/2007/08/19/removing-file-extension-via-htaccess
08. If You Want To Cover Both Http And Https
Options +FollowSymlinks RewriteEngine On RewriteCond %{HTTP_HOST}//s%{HTTPS} ^www.(.*)//((s)on|s.*)$ [NC] RewriteRule ^ http%3://%1%{REQUEST_URI} [L,R=301]
09. Create Custom Error Pages
ErrorDocument 400 /errors/badrequest.html ErrorDocument 401 /errors/authreqd.html ErrorDocument 403 /errors/forbid.html ErrorDocument 404 /errors/notfound.html ErrorDocument 500 /errors/serverr.html
10. Force Download Of Specific Files
<Files *.xls> ForceType application/octet-stream Header set Content-Disposition attachment </Files> <Files *.eps> ForceType application/octet-stream Header set Content-Disposition attachment </Files>
11. Log PHP Errors
# 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 /location/to/php_error.log
12. Require Password For 1 File
<Files login.php> AuthName "Prompt" AuthType Basic AuthUserFile /home/askapache.com/.htpasswd Require valid-user </Files>
13. Protect Multiple Files
<FilesMatch "^(exec|env|doit|phpinfo|w)\.*$"> AuthName "Development" AuthUserFile /.htpasswd AuthType basic Require valid-user </FilesMatch>
14. Compress Text Files
<ifModule mod_deflate.c> <filesMatch "\.(css|js|x?html?|php)$"> SetOutputFilter DEFLATE </filesMatch> </ifModule>
15. Cache-Control Headers
<ifModule mod_headers.c> <filesMatch "\.(ico|jpe?g|png|gif|swf)$"> Header set Cache-Control "max-age=2592000, public" </filesMatch> <filesMatch "\.(css)$"> Header set Cache-Control "max-age=604800, public" </filesMatch> <filesMatch "\.(js)$"> Header set Cache-Control "max-age=216000, private" </filesMatch> <filesMatch "\.(x?html?|php)$"> Header set Cache-Control "max-age=600, private, must-revalidate" </filesMatch> </ifModule>
16. Expire Headers
<ifModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 1 seconds" ExpiresByType image/x-icon "access plus 2592000 seconds" ExpiresByType image/jpeg "access plus 2592000 seconds" ExpiresByType image/png "access plus 2592000 seconds" ExpiresByType image/gif "access plus 2592000 seconds" ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds" ExpiresByType text/css "access plus 604800 seconds" ExpiresByType text/javascript "access plus 216000 seconds" ExpiresByType application/javascript "access plus 216000 seconds" ExpiresByType application/x-javascript "access plus 216000 seconds" ExpiresByType text/html "access plus 600 seconds" ExpiresByType application/xhtml+xml "access plus 600 seconds" </ifModule>
17. Turn ETags Off
<ifModule mod_headers.c> Header unset ETag </ifModule> FileETag None 20. Remove Last-Modified Header <ifModule mod_headers.c> Header unset Last-Modified </ifModule>
18. Redirect Www To Non Www Or Vice Versa
#redirect to non-www: RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^www.yourblogname.com [NC] RewriteRule ^(.*)$ http://yourblogname.com/$1 [L,R=301] #redirect to www: RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^yourblogname.com [NC] RewriteRule ^(.*)$ http://www.yourblogname.com/$1 [L,R=301]
Alternative way using generic domain:
RewriteEngine on RewriteBase / #redirect to non-www: RewriteCond %{HTTP_HOST} www.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] #redirect to www: RewriteCond %{HTTP_HOST} !^www. [NC] RewriteCond %{HTTP_HOST} ^(.+)$ [NC] RewriteRule ^(.*)$ http://www\.%1/$1 [R=301,L]
19. Speed Up Your Web site with .htaccess Caching
# 1 YEAR <FilesMatch "\.(ico|pdf|flv)$"> Header set Cache-Control "max-age=29030400, public" </FilesMatch> # 1 WEEK <FilesMatch "\.(jpg|jpeg|png|gif|swf)$"> Header set Cache-Control "max-age=604800, public" </FilesMatch> # 2 DAYS <FilesMatch "\.(xml|txt|css|js)$"> Header set Cache-Control "max-age=172800, proxy-revalidate" </FilesMatch> # 1 MIN <FilesMatch "\.(html|htm|php)$"> Header set Cache-Control "max-age=60, private, proxy-revalidate" </FilesMatch>
20. Block Referring Domains
#block referring domains RewriteEngine on RewriteCond %{HTTP_REFERER} digg\.com [NC] RewriteRule .* – [F]
21. Redirect Visitors To A Maintenance Page
RewriteEngine on RewriteCond %{REQUEST_URI} !/maintenance.html$ RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123 RewriteRule $ /maintenance.html [R=302,L]
22. Password-Protect Single File
<Files secure.php> AuthType Basic AuthName "Prompt" AuthUserFile /home/path/.htpasswd Require valid-user </Files>
23. Password-Protect Multiple Files
<FilesMatch "^(execute|index|secure|insanity|biscuit)*$"> AuthType basic AuthName "Development" AuthUserFile /home/path/.htpasswd Require valid-user </FilesMatch>
24. Redirect Any Request For Anything From Spamsite To Differentspamsite
RewriteCond %{HTTP_REFERER} ^http://.*spamsite.*$ [NC] RewriteRule .* http://www.differentspamsite.com [R] Redirect All Requests From Spamsite To An Image Of Something At Differentspamsite RewriteCond %{HTTP_REFERER} ^http://.*spamsite.*$ [NC] RewriteRule .* http://www.differentspamsite/something.jpg [R] Redirect Traffic From A Certain Address Or Range Of Addresses To Another Site RewriteCond %{REMOTE_ADDR} 192.168.10.* RewriteRule .* http://www.differentspamsite.com/index.html [R]
Conclusion
These .htaccess code snippets are really very common when you go for configuring your server. But when you are using .htaccess files beware that it can be disastrous for your website if you do not use it correctly. So you should be careful when you modify your .htaccess file as a single character in this file can make your server unavailable to the users. And for that make sure that you have backed up the last modification of .htaccess to go back if any problem occurs. Try to modify these .htaccess code snippets as your need.
You can also have a look at another post named – Common .htaccess code snippets for WordPress. This post contains most common .htaccess code snippets for WordPress blog.
The post Common .htaccess code snippets appeared first on JS Tricks.