Examples of .htaccess settings
What is an .htaccess file and why is it needed?
Features of the .htaccess file
Redirection (redirect)
Barring web access / ban on IP
Some tips for working with the .htaccess file
What is a .htaccess file and what is it used for?
.htaccess - is a special configuration file of the apache web server, that gives you a possibility to change the apache web servers settings for separate folders, without access to the main configuration file.
A file .htaccess can be created in any catalogue and it`s settings will affect all the files in this catalogue and all its subcatalogues.
File .htaccess features
Main file parameters:
- Simple redirect;
- Complex redirect (mod_rewrite);
- Index pages;
- Error processing;
- Encoding detection;
- Access management to files and directories;
- Directory passwords;
- PHP options.
.htaccess setup examples
Redirect
Redirect to another address:
Redirect only when certain pages are requested:
Redirect example.com на www.example.com :
RewriteCond !^www\..* [NC]
RewriteRule ^(.*) http://www.{HTTP_HOST}/$1 [R=301]
And vice versa:
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
Redirect only visitors with a certain IP (XXX.XXX.XXX.XXX):
RewriteCond %{REDIR} redir
RewriteRule ^/$ /page.html
Apache error processing:
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
If these errors occur, the site visitor will be redirected to specially created pages.
Redirect to the safe HTTPS connection:
RewriteCond !on
RewriteRule (.*) https://{HTTP_HOST}%{REQUEST_URI}
Web access forbidden / IP ban
Web access denied:
Deny from all
Denied all web access except IP (XXX.XXX.XXX.XXX):
Deny from all
Allow from xxx.xxx.xxx.xxx
Deny access for IP (XXX.XXX.XXX.XXX):
Allow from all
Deny from xxx.xxx.xxx.xxx
Prevent access to files with multiple types of extensions:
deny from all
</Files>
Deny access to a specific file (secret.php):
deny from all
</Files>
You can also deny web access to a range of IP addresses:
Deny from 192.168.0.0/16
Other settings
Disable directory browsing without index files:
Change of index page that loads by default:
Some tips for working with a file .htaccess
- Make changes step by step, so that if something goes wrong, you can quickly find a problem.
- Always backup the file, so you can restore it, if changes don`t work or didn`t save.
- After changing the file and checking the website, it is desirable to clean browser cash, because old settings might still be cashed .
- The most common web server error while working with .htaccess — 500, and either it indicates a problem in the syntax (misprint in directive, for example), or the main configuration file does not allow this type of directive.
If you are not satisfied with all the settings of the file .htaccess - You may be interested in ordering a private virtual server. On them, you can make changes directly to the Apache settings. Our offers for virtual private servers are suitable for any user.