How to prevent viewing the contents of a specific folder. What is htaccess used for?


Before you start making any changes to the htaccess file, you need to understand what kind of file it is and what it is needed for. In short, this file is responsible for configuring the web server settings. In other words, it contains information about how the web server should process certain pages on the site.

What is htaccess used for?

In most cases, the htaccess file is used to create a redirect, or in other words, a 301 redirect from one page of a site to another. But this is not all the possibilities this file, you can also use it to tell the web server (Apache and similar servers) to compress pages, enable caching, control access to directories, and much more.

Since for users who have placed their sites on virtual hosting, it is not possible to directly configure a web server (since this will affect all sites hosted on it), then the htaccess file was invented to configure the server for each site separately.
Where should the htaccess file be located?

After Joomla installations 3 on your local computer or hosting, the root directory of the site already contains the file htaccess.txt, but in order for it to start working, it must be renamed. The name of the working file must begin with a dot, followed by the name “htaccess” and that’s it, there should not be a “.txt” extension. The resulting file should be named “.htaccess”.

Regarding its location, everything is simple - if the file is in root directory site, then its actions apply to the entire site. But no one forbids placing the htaccess file in subfolders, thereby the file’s action will only apply to them and subfolders. It is also possible to use multiple htaccess files in different folders, for example, in the root of the site and in a subfolder. In this case, the action of the main file will apply to the entire site, with the exception of the directory in which it is located. own file configurations.

What directives does the htaccess file contain?

There can be many directives; in the basic version, the htaccess file, which is already present in Joomla 3, contains (if all comments are removed) approximately the following code:

IndexIgnore * #Exclude files from the listing Options +FollowSymlinks # This line designed for correct redirection. Options -Indexes #Prohibit viewing directories in which there are no index files RewriteEngine On #Enable the redirection mechanism in the mod_rewrite.c module ## Security settings RewriteCond %(QUERY_STRING) base64_encode[^(]*\([^)]*\) RewriteCond %( QUERY_STRING) (<|%3C)([^s]*s)+cript.*(>|%3E) RewriteCond %(QUERY_STRING) GLOBALS(=|\[|\%(0,2)) RewriteCond %(QUERY_STRING) _REQUEST(=|\[|\%(0,2)) # If one of conditions described above, the server will return a 403 error and redirect to the main page of the site. RewriteRule .* index.php [F] #This line is responsible for this ## Block dedicated to SEF optimization. RewriteRule .* - RewriteCond %(REQUEST_URI) !^/index\.php RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule .* index.php [L]

This concludes the review of the basic htaccess file finished. Now you know that in order for a file to start issuing instructions to the web server, it must first be renamed. Base file htaccess is quite functional and will be fine to start with.

In the next article, I will talk about other useful htaccess file directives that will allow you to protect your site, enable compression and caching of its pages, and some other useful functions.

Level: Newbie - User

Hello, dear subscribers. Let us remind you that the SEF function, which we are talking about today, allows you to generate links to internal pages of the site in the form of static addresses. And by default, Joomla creates dynamic links to internal pages. What is the difference dynamic addresses from static and why static page addresses are more useful for your site, read in our newsletter.

In the standard Joomla distribution, the SEF function is provided, but is not enabled automatically. You can activate it quite simply and quickly. Let's describe the process step by step.

Step 1. Enable the SEF option in the Joomla admin panel

Select a menu item Home > Global configuration and open the tab SEO. Next for the parameter Friendly for search engines URLs set the value Yes. Joomla will warn you: “You need to rename htaccess.txt to .htaccess.” Close the warning window and move on.

Step 2: Optional. In case the address of the main page of your site contains an additional path

Let's explain. If on your site for download home page just enter in the browser www.mysite.ru, then you DO NOT need to do this step!
Who needs it? An example is nearby. To access our newsletter site, to get to Joomla, you need to type the address www.site/joom/ What additional needs to be done for such sites? Set in file htaccess.txt parameter RewriteBase With correct value. Typically the RewriteBase parameter looks like this:

RewriteBase /

or can be commented out:

# RewriteBase /

You need to uncomment the parameter and write it like this:

RewriteBase /<имя_папки_джумлы>/

For site website the change will look like this:

RewriteBase /joom/

Attention! To change a file htaccess.txt he must have unix rights allowing him to do this. For security reasons, this file must have "444" permissions. But in this case you cannot change it. To change, permission "644" is required. Install them, and after changing, BE SURE to return the previous rights!
One more moment. File htaccess.txt may be encoded KOI8, so you can’t work with it in Notepad; you need any other editor that accepts this encoding.

Step 3. Rename the htaccess.txt file

File htaccess.txt located in the root folder of Joomla. You can rename it in 2 ways. If your distribution has a component Joomla Xplorer, you can rename the file using it. Another method is universal. Login to hosting ftp and do what is required. Rename the file htaccess.txt V .htaccess

Technical points

Before enabling SEF, you need to consider the following points:

  • If you use Unix hosting and, accordingly, the Apache web server, then the module must be enabled in its configuration mod_rewrite. On normal hosting it is usually enabled.
    At using Windows hosting, which is very rare, it is necessary to clarify the availability of an analogue of mod_rewrite.
  • For Unix hosting, configuration overlapping must additionally be allowed apache web server in user configuration files .htaccess This is also usually already installed

Notes:

1. Check technical issues with hosting technical support.

2. The SEF function is as easy to disable as it is to enable it by doing the above steps in reverse order. Therefore, it is not necessary to clarify technical issues before enabling SEF. If, after enabling SEF, page addresses are generated in the same way or to internal pages access to the site will be terminated, a “Page not found” window will be displayed, just return everything to its previous state and the site will be restored!

Lyrical digression:)

As such, let me invite you to get acquainted with the news resource Holidays all year round!, created by the "efft" Lab team. This is the news from the most popular tourist destinations of the coming season:

Do you know what percentage of our country's population vacations abroad? 10 - 20 - 30? No! How much? .

© www.. All rights reserved
When reproducing article materials, indicate the author's name
and an active link to the site are MANDATORY!

The .htaccess file (English hypertext access) is used for simple and convenient setup web server on which the user's website is stored. By changing the web server settings accordingly, we can change the operation of the site. Typically, the .htaccess file is located in the root directory, and its effect applies to the entire site and all subdirectories. If another directory contains its own .htaccess, then it will only act on its own directory and subdirectories.

Important! Changing the .htaccess file can greatly disrupt the operation of the site, and rash actions with it may not have visible consequences, but may lead to a decrease in positions in search engines, or their complete loss. Therefore, we recommend that before making any changes to the file, save a copy of it in order to be able to return the previous settings.

Where is the .htaccess file located?

Usually it is located in the root directory of the site. Sometimes, in various CMS there may be a file htaccess.txt, which is not perceived by the server in any way and does not affect anything. For it to start working, you need to rename it to .htaccess. If this cannot be done on your computer, then go to your server via an FTP client and rename the file directly on the server.

You can edit the file on your computer using any text editor, but to avoid possible problems with encoding, we recommend using Notepad++ for this.

How to check if .htaccess is working?

It's simple, write any word in the first line of this file (for example YAROBOT), save the file and replace it with the one located on the server. If the site continues to work, then .htaccess in this moment does not work. If error 500 appears Internal Server Error, this means that the web server could not understand the command (YAROBOT) and generated an error. This fact will confirm that .htaccess work on the server is supported and enabled at the moment. To return the site to functionality, remove the line from YAROBOT.

Correct 301 redirect via .htaccess file

Important! If you want your redirect to work, you need to write before the lines that are recommended below in the text:

301 Redirect from one page to another (or site)

To do this, add to the .htaccess file following lines:

Redirect 301 /old-page.html http://site.rf/new-page.html

RedirectPermanent /old-page.html http://site.rf/new-page.html

301 Redirect from www site to site without www

For example, redirecting from http://www.site.com to http://site.com. This is a very useful thing, often used in SEO

Options +FollowSymLinks
RewriteEngine On
RewriteCond %(HTTP_HOST) ^www.domain\.com$
RewriteRule ^(.*)$ http://domain.com/$1

Reverse redirect from a domain without www to a domain with www

Redirection from http://site.com to http://www.site.com (we do not recommend using it)

Options +FollowSymLinks
RewriteEngine On
RewriteCond %(HTTP_HOST) ^domain\.com$
RewriteRule ^(.*)$ http://www.domain.com/$1

Redirect all visitors from the old site to the new one

Redirect 301 / http://newsite.com/

How to add .html at the end of the URL?

So that when you enter site.com/page or site.com/page/, a redirection to site.com/page.html occurs, write the following in .htaccess:

RewriteCond %(REQUEST_URI) (.*/[^/.]+)($|\?)
RewriteRule .* %1.html
RewriteRule ^(.*)/$ /$1.html

How to remove .html at the end of the URL?

Reverse redirect from site.com/page.html to site.com/page

RewriteBase /
RewriteRule (.*)\.html$ $1

How to remove the slash at the end of the URL?

For example, it was site.com/page/, it became site.com/page

RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^(.+)/$ /$1

301 Redirect from one section to another?

Redirecting all pages of one section site.com/razdel-1/razdel-2/page to pages of another section site.com/razdel-1/page

RewriteRule ^blog/raznoe/(.*)$ http://site.ru/blog/$1

301 Redirect when moving from an old domain to a new one

The following rule will correctly redirect visitors from each specific page of the old site to the same page on the new site. For example from oldsite.com/page to newsite.com/page

RewriteCond %(HTTP_HOST) ^www.oldsite.com$
RewriteCond %(HTTP_HOST) ^test.oldsite.com$
RewriteRule ^(.*)$ http://newsite.com/$1

Correctly changing error pages via .htaccess

When a user wants to see a site (sends a request to the hosting server), the server returns a response with a code. Codes 1-399 indicate normal operation server, and codes 400-599 indicate a server error (see the special article for all error codes). For example, if the server with your site is overloaded or is rebooting, the user will see text that he does not understand (for example, 500 Internal Server Error), will think that the site will no longer work and will never return to it. To instead standard page errors (not clear to the user) show him your separate page, on which there will be, for example, a message that the site is temporarily not working, but will later restore its operation and you should definitely return to it (the KinoPoisk site, when the servers are overloaded, displays the message “The Matrix is ​​reloading...” and the corresponding picture). The most common solution is to compose own page instead of the standard 404 error. This error is shown to the user if the address of a non-existent page is entered. Thinking webmasters create their own page instead of the incomprehensible standard one, on which they write that the person followed a non-existent link and suggest searching necessary information on the site, rather than leaving it. An example of our 404 page can be seen. To show users your own error page instead of the standard one, you need to create a separate page (for example http://yoursite.com/404.html) and add the appropriate code to the .htaccess file. Here are examples of the code you need to add:

ErrorDocument 400 http://yoursite.com/400.html
ErrorDocument 404 http://yoursite.com/404.html
ErrorDocument 500 http://yoursite.com/500.html

If you want to substitute another page instead of the 403 error, then you need to specify text message which will be shown, for example:

ErrorDocument 403 "Sorry can"t allow you access today, see you later alligator:)"

Site security settings via the .htaccess file

The .htaccess file provides great opportunities to improve site security. We will now list the most popular ones:

Protecting your website from script injections

#Enables tracking of SIM links
Options +FollowSymLinks
#Starts url_rewriting
RewriteEngine On
#Blocks all links containing ‹script›
RewriteCond %(QUERY_STRING) (\<|%3C).*script.*(\>|%3E)
#Blocks all scripts that try to change PHP variables Globals:
RewriteCond %(QUERY_STRING) GLOBALS(=|\[|\%(0,2))
#Blocks all scripts that try to change the _REQUEST variable:
RewriteCond %(QUERY_STRING) _REQUEST(=|\[|\%(0,2))
#Redirects all such attempts to a 403 error page - forbidden
RewriteRule ^(.*)$ index.php

How to protect your website from image theft

Often skilled webmasters find out the path to the image on your site and insert it into the code of their page. As a result, the main page is loaded from his server, and the image is loaded from yours. This allows him to save his traffic and use yours.

Options +FollowSymlinks
#Prohibits the theft of pictures
RewriteEngine On
RewriteCond %(HTTP_REFERER) !^$
RewriteCond %(HTTP_REFERER) !^http://(www.)?yoursite.com/
RewriteRule .*.(gif|jpg|png)$ http://yoursite.com/images/stop_stealing.gif

yoursite.com - your website address
http://yoursite.com/images/stop_stealing.gif - the path to the image that you must create yourself. It usually says “don’t steal pictures from other people’s sites” or something similar.

How to block access to a site for a user via IP?

It is used against spammers and other inappropriate people, and occasionally to prevent hacker attacks.

#Insert unwanted IP addresses here
allow from all
deny from 164.186.15.116
deny from 124.153.34.144

How to block access to a site for all IPs except verified ones?

To block access for everyone except specific IP addresses, add the following code:

#Deny access for everyone except the specified IP addresses
ErrorDocument 403 http://www.yoursite.com
Order deny,allow
Deny from all
Allow from 164.186.15.116
Allow from 124.153.34.144

How to prevent viewing the contents of a specific folder

#Disables viewing the contents of the folder
Options All -Indexes

Denying access to a specific file

#Protects the file myfile.txt

order allow,deny
deny from all

Deny access to all files with a specific extension

For example, to deny access to all .txt files we write this:


Order Deny,Allow
Deny from all

Blocking unnecessary User Agents

Often the user has a lot of extensions installed in his browser, which transmit information about himself and other unnecessary information to the server (on which your website is located). The same information is sent to the server by client applications installed on the user’s computer, as well as various robots and spiders. Information about most of the current "User Agents" can be found.

#Blocks the following User Agents
SetEnvIfNoCase user-Agent ^FrontPage
SetEnvIfNoCase user-Agent ^Java.*
SetEnvIfNoCase user-Agent ^Microsoft.URL
SetEnvIfNoCase user-Agent ^MSFrontPage
SetEnvIfNoCase user-Agent ^Offline.Explorer
SetEnvIfNoCase user-Agent ^ebandit
SetEnvIfNoCase user-Agent ^Zeus

Order Allow, Deny
Allow from all
Deny from env=bad_bot

Changing the site encoding via .htaccess

It happens that one user comes to your site and sees it as normal, while another sees gobbledygook instead of letters. This happens due to the site's encoding. In order for the user’s browser to recognize it correctly, the site is made in one of the popular encodings:

UTF-8 - universal double-byte encoding
Windows-1251 - Cyrillic (Windows)
KOI8-r - Cyrillic (KOI8-R)
cp866 - Cyrillic (DOS)
Windows-1250 - Central Europe (Windows)
Windows-1252 - Western Europe(Windows)

Also, the encoding must be indicated in the meta tag of each page of the site, this tells the browser what encoding the site is made in.

If this meta tag is not specified, you can tell the browser what encoding you have using the .htaccess file:

AddDefaultCharset WINDOWS-1251

If both options work (both the meta tag and the .htaccess file), then it is very important that the encoding in them matches.

It is also possible for the server to automatically transcode all files that are uploaded to it:

To disable server recoding you need to enter:

Optimizing the site using .htaccess

Speeding up a website using Gzip

Enabling this feature allows the server to compress information before it sends it to the user. As a result, the speed of the site will increase, but this will slightly increase the load on the server (on which your site is stored), because he will have to perform the compression operation on the fly. To enable Gzip compression, you need to add the following lines to the .htaccess file (try adding 3 code options one by one, checking the speed, and leave the option that gives the greatest speedup):


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 no-gzip
BrowserMatch bMSIE !no-gzip !gzip-only-text/html

mod_gzip_on Yes
mod_gzip_item_include file \.js$
mod_gzip_item_include file \.css$

FileETag MTime Size


ExpiresActive on



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

How to improve website caching on the server?

Improved caching makes it possible not to download data a second time (pictures, basic design elements, etc.) that were already downloaded by the user when they first viewed the site. Thus, for a particular user, the second and subsequent pages viewed will load much faster, and the load on your server will be significantly reduced. You can improve site caching using the following code (try two options in turn, and leave the fastest one, check the speed):


Expires Active On
ExpiresByType application/javascript "access plus 7 days"
ExpiresByType text/javascript "access plus 7 days"
ExpiresByType text/css "access plus 7 days"
ExpiresByType image/gif "access plus 7 days"
ExpiresByType image/jpeg "access plus 7 days"
ExpiresByType image/png "access plus 7 days"
FileETag MTime Size


ExpiresActive on
ExpiresDefault "access plus 1 month"

In the "access plus ..." expression, set the storage period for files on the user's computer. After this period, when a request is made to the site, the files will be downloaded one-time from the server. The optimal period would be from 7 days to a month, although sometimes a year is set.

Changing the main (index) page of the site

Typically, when you access a website, the index.html or index.php page is loaded first. To change this rule (mypage.php will load first), add the following code to .htaccess:

Configuring PHP parameters via the .htaccess file

Usually for PHP settings The php.ini file is responsible, but some of these settings can be set via .htaccess. For this, two expressions are used: php_value - for logical values ​​(for example, enable/disable), and php_flag for numerical values. Here are the rules for writing these expressions:

php_flag directive1 VALUE1
php_value directive2 VALUE2

where VALUE1 can be on, off, 1 or 0 (1 and on mean turn on, and 0 and off mean turn off);

VALUE2 - any numeric or alphabetic value that matches a specific directive;

directive1 (only used with php_flag) can have the following values:

magic_quotes_gpc - enable/disable the magic_quotes_gpc function


display_startup_errors - enable/disable display of errors that occur while running PHP

php_flag display_startup_errors 1


display_errors - on/off displaying errors in the browser


output_buffering - enable/disable data output buffering


register_globals - enable/disable global variables


engine - on/off PHP execution in the folder in which .htaccess is located and in all subfolders

directive2 (only used with php_value) can have the following values:


upload_max_filesize - sets maximum size downloadable file

php_value upload_max_filesize 10M


user_agent - sets the value of the user_agent string sent by the server

php_value user_agent “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)”


post_max_size - sets the maximum size of forwarded mail


mysql.default_user - specifies the database user name

php_value mysql.default_user databaseuser


mysql.default_password - sets the password for the database user

php_value mysql.default_password jk323jh4g


mysql.default_host - specifies the database host name (usually localhost)

php_value mysql.default_host localhost


sendmail_from - sets the email to send mail using PHP


auto_prepend_file - specifies the file that will be added to the beginning of each PHP script

php_value auto_prepend_file /www/public_html/myfile.php


auto_append_file - specifies the file that will be appended to the end of each PHP script

php_value auto_append_file /www/public_html/myfile.php
At the root of every site there is a file called “.htaccess”. Novice webmasters do not attach any importance to it. To be honest, for the first year and a half I also didn’t understand why it was needed. I was laying the htaccess.txt file in a folder and messing around. And then, when I started delving into website promotion, I realized that I couldn’t live without anyone. And I had to rename the htaccess.txt file to .htaccess, thereby activating it (in the first option it does not work). And then I began to understand teams. As it turns out, there are many useful commands that can make a webmaster's life easier. I will now share some of them with you.

Yesterday forced me to delve deeper into the knowledge of the .htaccess file. introduction to Joomla 3.0 , in which slashes appeared by themselves.

301 redirect/Redirect 301:

I'll probably start with the most useful command for SEOs - 301 redirects. Personally I use this command on each of your own and client sites, at a minimum, to glue the domain with and without WWW, as well as to hide referral links.

This is done like this:

Redirect 301 /referal http://www.site.com/category/page/1

Error 404:

Almost every CMS has its own 404 error page. The easiest way, in my opinion, is to create it yourself and register it in htaccess.

ErrorDocument 404 / 404.html

Hiding folders and files:

To secure your site, you can hide certain directories and files.

Options All -Indexes

Protecting yourself from hotlinking:

If your site has a lot of useful and unique materials, and they are updated frequently, then sooner or later they will start to be copied. And the “thieves” are too lazy to even transfer images to their website. Therefore, when an image is loaded on their site, it will be loaded from your server. This is called hotlinking. To protect your site from it, you should make changes to htaccess.

RewriteBase /
RewriteCond%(HTTP_REFERER)^$!
RewriteCond%(HTTP_REFERER)^http://(www.)yoursite.com/*$!?.
RewriteRule (GIF | JPG | SWF | FLV | PNG). $/feed/

Changing the default page:

Many hosting sites allow you to specify a default page in the admin panel (for example, instead of the main page, a product category page), but some do not. Therefore, it is easiest to indicate desired page in one file. For example, the page about " banner advertising on the Internet" If you move to any other hosting, the default page will not change.

DirectoryIndex about.html

Set up a redirect from domain to domain:

It's no secret that sites have to be closed sooner or later. The reasons may be different. In order not to lose traffic from search engines, you can set up a redirect from the old domain to the new one. A regular 301 redirect will not work here.

# redirect from old domain to new domain
RewriteEngine On
RewriteRule ^(.*)$ http://www.yourdomain.com/

Set the file upload limit:

If you have a popular forum or website where users constantly upload photos, videos and other files, then you have most likely already encountered a lack of disk space on the server. To postpone this moment until a later date, I recommend specifying the maximum size for uploaded files with the following commands:

php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200

Compress files:

Of course, you can enable GZIP file compression in your CMS; for example, Joomla allows you to do this. But if your CMS is not capable of this, then you can enable file compression with the following commands in the htaccess file:

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

Enable file caching:


Header set Cache-Control “max-age=2592000″

Set up the site administrator's email:

ServerSignature EMail
SetEnv SERVER_ADMIN This e-mail address protected from spambots, you must have Javascript enabled to view it

You may also find my article “ How to glue a domain correctly ».


Leave a comment, click " I like» (« Like") And " Save“, and I’ll write something else interesting for you :)







2024 gtavrl.ru.