Useful hacks and snippets for .htaccess



This is a translation of a very interesting article for me personally , which I want to share with the respected habrasociety. I already met some of the given recipes on Habré, but not all of the following are fragmented and far from all.

Every web developer knows about the purpose of the .htaccess file. At a basic level, it allows you to control access to site directories. But adding various additional code fragments to it, you can do many other interesting things with it.

If you need basic information about the purpose of this file, then you can get an introduction to .htaccess from our article (I didn’t translate this article, because there are the basics, there are enough of them in the Russian-language segment of the Network, but if you show interest, you can translate it to complete the picture - approx. translator ), in which all aspects of its application are sufficiently detailed.

So, useful usage examples. htaccess:

1. Control access to files and directories

Password protection is one thing, but sometimes it may be necessary to completely block user access to a specific file or folder. This usually refers to system folders, such as includes, for example, which applications should have access to, but not users.

To do this, put the given code in a file. htaccess and save it in the directory to which you are denying access:

deny from all

However, keep in mind that access will be blocked for all users, including you. You can open access for a specific user by registering his IP address. Here is the code you need for this:

order deny,allow 
deny from all 
allow from xxx.xxx.xxx.xxx

where is xxx. xxx. xxx. xxx is your IP. You can replace the last three digits to specify the allowed ranges of IP addresses. For example, writing “0/12” instead of them, you specify a range of IP addresses for one network, which saves you from having to enter all allowed IP addresses separately.

If you want to block access to a specific file, including itself. htaccess, use the following code snippet:


 order allow,deny
 deny from all
 

If you want to specify specific IP addresses that should be denied access, list them using allow from.

If you want to block access to files of a certain type, use this code:


 Order Allow,Deny
 Deny from all
 

2. Prohibition of viewing directories

To prevent viewing the site directories, add the following code to .htaccess:

Options All -Indexes

If for some reason you want to allow viewing of all directories, use the code:

Options All +Indexes

3. Faster download times by compressing files

You can compress files of any type. For example, to compress HTML files, add the code:

AddOutputFilterByType DEFLATE text/html

To compress text files use:

AddOutputFilterByType DEFLATE text/plain

You can also compress JavaScript or enable compression for other various types of files with commands:

AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml

In addition, you can compress all your JavaScript, HTML and CSS files using GZIP. To do this, use the following code:


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.* 

4. Protecting the site from inserting images from other resources

If you want to prohibit adding links to images from third-party resources, add the code to the .htaccess file:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

Remember to replace yourdomain.com with your domain name.

5. Block visitors from a specific domain

If you do not want to see users from a specific domain on your site, then you can deny them access. For example, you can redirect users from unwanted resources (adult sites, hacker sites, etc.) to the 403 Forbidden page. To do this, you must enable mod_rewrite, although, as a rule, it is enabled by default. Add the code to .htaccess:


RewriteEngine on
RewriteCond %{HTTP_REFERER} bannedurl1.com [NC,OR]
RewriteCond %{HTTP_REFERER} bannedurl2.com [NC,OR]
RewriteRule .* - [F]

You need to replace bannedurl1.com and bannedurl2.com with the domains you want to blacklist. You can use the [NC] flag to indicate that the entered domain name is case-insensitive. The [F] flag indicates the type of action, in this case, the display of 403 Forbidden errors. If you want to prohibit several sites, use the [NC, OR] flags for each domain; if you want to prohibit the use of one domain, use only the [NC] flag.

6. Blocking requests from certain browsers

If records about visiting special browsers appear in your log files (these can be bots or spiders imitating the browser), you can prevent them from accessing your site by adding a few lines to. htaccess:

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

Replace badbot1, badbot1, etc. with the bot names from your log. This will block unauthorized programs from accessing your site.

7. File Caching

File caching is another way to speed up the loading of your site. Here is what you need to register in .htaccess:


Header set Cache-Control "max-age=2592000"

You can add more file types (or delete some of them) to the list of files listed in this example. You can also specify the time to save files in the cache (in seconds) using the max-age variable.

8. Disabling caching for different types of files

If you do not want to cache certain types of files, you can omit them from the list. However, sometimes files can be stored in the cache without even being explicitly listed, in which case you can disable caching for them individually. Most often, disabling caching is required for dynamic files, such as scripts. An example required for this code:

Header unset Cache-Control

Just specify the file types for which you want to disable caching.

9. Bypassing the download dialog

By default, when you try to download a file from a web server, a dialog is displayed asking you if you want to save the file or open it. This dialog is especially annoying when downloading large media or PDF files. If the files you uploaded to the server are for download only, you can make life easier for users by setting the default download action. Add to. htaccess is the following:

AddType application/octet-stream .pdf
AddType application/octet-stream .zip
AddType application/octet-stream .mp3

10. Rename the .htaccess file

If for some reason you want to rename the .htaccess file, then you can do it. Theoretically, renaming a .htaccess file should not cause problems with applications running on your server, but if you notice script errors after renaming a file, just rename it back.

AccessFileName htac.cess

In addition, you must update all entries that mention the .htaccess file, otherwise many errors will occur.

11. Replacing the start page of the site

If you want to set the main page different from the standard one (index.html, index.php, index.htm, etc.), add the following code to the .htaccess file:

DirectoryIndex mypage.html

Replace mypage.html with the URL of the page you want to use as your homepage.

12. Redirect to secure HTTPS connection

If you use HTTPS and want to redirect users to secure pages of your site, add the following lines to the .htaccess file:

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

13. Limiting the maximum size of downloaded files in PHP, the maximum size of the transmitted data, the maximum execution time of scripts, etc.

.htaccess allows you to set some values ​​that directly affect the operation of PHP applications. For example, if you want to set a restriction on the size of downloaded files in PHP so as not to clog hosting with large files:

php_value upload_max_filesize 15M

You can set any value, in the example the file size is limited to 15M (MB). In addition, you can limit the maximum size of data transferred when loading into PHP:

php_value post_max_size 10M

You can replace 10M with any value you require. If you do not need constant execution of scripts, you can limit the time of their execution using the line:

php_value max_execution_time 240

240 - runtime (in seconds) after which the script will be stopped, you can change this value to any other. Finally, if you want to limit the analysis time to the source data script, use the following code:

php_value max_input_time 180

Instead of 180, set whatever time you need (in seconds).

14. Hiding file types

Sometimes you need to prevent users from knowing what types of files are on your site. One way to hide this information is to make all your files appear as HTML or PHP files:

ForceType application/x-httpd-php
ForceType application/x-httpd-php

And this is only part of what .htaccess can do, but in general it allows you to do much more. For example, you can set automatic translation of pages on your site, set the time zone of the server, remove the WWW from URLs, or use fancy directory views, etc. But in any case, before you start experimenting with the .htaccess file, always keep a backup of the original .htaccess, so that in case of problems you can quickly restore the site. UPD

source (thanks akuma ) The PHP extension for hiding the file format is given as an example and using this trick in a real project may be unsafe


Also popular now: