How to create an htaccess file. How to create a .htaccess file - detailed instructions for beginners

When creating websites, you often need to create an .htaccess file. When I first started working with website building, I encountered some problems that made it difficult for me to create htaccess. I’ll tell you about them, and how to create this file.

Problem

In general, .htaccess is an additional Apache configuration file. Its peculiarity is that this file has only an extension, without a name. This causes some difficulties.

1. You want to create an htaccess file on your Windows computer. The file configuration does not show their extension. You create a text file and call it .htaccess. You enter all the necessary information there, but it turns out that none of it works. In fact, you just created a text file, not the required one.

2. The first case, but only your file extensions are shown and you change “New text document.txt” to “.htaccess”. The following error appears.

How do you create this file?

Solution

1. You can just download ready htaccess. For example, for CMS wordpess can be downloaded from the link. If you have a different content management system, you can simply delete all the contents of the file and customize it for yourself. You can also download a blank htaccess.

134bytes Number of downloads: 266

2. You can create htaccess in file manager, which you use to communicate with the hosting (server), for example WinSCP. New -> File

For editing, I recommend using a text editor. If you know other ways, you can add to the topic.

Supported by.

The .htaccess file allows you to set website configurations without having to change server configuration files. A dot at the beginning of a file name means that the file is hidden.

The .htaccess file can be created in a text editor, and then uploaded to the site using an ftp client

Note: The .htaccess file name does not contain any additional words or extensions.

In addition, the location of such a file is also of great importance. The configurations in this file will affect the entire contents of the directory in which the file itself is located, as well as all its subdirectories.

File Features.htaccess

While the .htaccess page is incredibly useful and can greatly improve your site, there are two things to keep in mind when using it.

Firstly, it's speed. The .htaccess page may slow down the server speed slightly; in most cases it is almost unnoticeable. This is due to the layout of the page: as mentioned, the .htaccess file affects pages and subdirectories within its directory. Every time a page is loaded, the server checks its directory, as well as each directory above it, until it reaches the highest directory or .htaccess file. This process will continue as long as the AllowOverride setting allows the use of .htaccess files, regardless of whether such files even exist on the system.

Secondly, it's safety. The .htaccess file is much easier to access than a regular Apache configuration file, and changes made to it will be activated immediately, without the need to reboot the server. Therefore, users who have rights to make changes to the .htaccess file can seriously influence the server itself. Any directive added to .htaccess has the same effect as a directive added directly to the Apache configuration.

How to include a file.htaccess?

With access to server settings, you can edit Apache configurations to allow .htaccess files to override standard site configs. Open the default apache2 host configuration file.

Note: You will need sudo privileges at this stage.

sudo nano /etc/apache2/sites-available/default

With the file open, find the following section and change the value of the AllowOverride directive from None to All. The section should look like this:


Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all

Save and close the file and then restart apache.

sudo service apache2 restart

Creationfile.htaccess

As already mentioned, the .htaccess file can be created using a text editor, and then uploaded to the site via an ftp client (the name of the .htaccess file should not contain additional words or extensions).

Or you can create such a file using the terminal; To do this, use the following command, replacing example.com with the site name.

sudo nano /var/www/example.com/.htaccess

Common uses of .htaccess

1. Mod_Rewrite

One of the most useful aspects of the file. The .htaccess file space can be used to define/change the way URLs and web pages are displayed on a site. Detailed information on how this is done can be found at this link.

2. Authentication

Although the .htaccess file does not require as many rights as the standard apache2.conf configuration file, it can still be used to make effective changes to your site's security. The fact is that .htaccess allows you to request a password to access certain sections of the web page. The .htaccess passwords are stored in a file called .htpasswd.

Note: For security reasons, storing such a file in the site directory is strictly not recommended.

In the .htpasswd file you need to specify the names and passwords of all users who are allowed access to the secure part of the site.

Usernames and passwords are entered into the file as a pair user_name:encrypted_password. For example, if a user named best_user has a password of awesome, then such a pair might look like “best_user:VtweQU73iyETM”.

Note: Each pair is entered on a separate line. The .htpasswd file can contain as many lines as necessary.

Once you have created .htpasswd, add the following code to .htaccess to enable the authentication feature:

AuthUserFile /usr/local/username/safedirectory/.htpasswd
AuthGroupFile /dev/null
AuthName Please Enter Password
AuthType Basic
Require valid-user

Line AuthUserFile defines the path to the .htpasswd file.

Line AuthGroupFile specifies the location.htgroup. Since no such file currently exists, leave it at /dev/null.

Line AuthName contains the text that will be displayed in the password prompt (you can enter absolutely any text).

AuthType refers to the type of authentication that will be used to verify passwords. Passwords are checked via HTTP and the Basic keyword cannot be changed.

Line Requirevalid-user tells the .htaccess file that multiple people should have access to password-protected sections of the site. If you need to specify a specific person who has access to restricted parts of the site, instead of the Require valid-user line, the Require user line is used Username.

3. Custom error pages

The .htaccess file allows you to create custom error pages for your site. Some of the most common mistakes are:

  • 400 Bad Request
  • 401 Authorization Required
  • 403 Forbidden Page
  • 404 File not Found
  • 500 Internal Error

Custom error pages are created with the goal of making site pages friendlier and providing more detailed information to the site visitor than the default server error pages.

For example, you can create a 404 page (try creating any error page of your choice).

After creating and loading the error page, specify its location in the .htaccess file:

ErrorDocument 404 /new404.html

Remember: Apache looks for a 404 page in the root directory of the site. When placing a new 404 error page in any subdirectory, be sure to add that subdirectory to the line, for example:

ErrorDocument 404 /error_pages/new404.html

4. MIME types

In cases where the site hosts some application files that the server has not been configured to display, the MIME types for the Apache server can be added to the .htaccess file using the following code:

AddType audio/mp4a-latm .m4a

Be sure to replace the application and file extension with the MIME type you want to support.

5.SSI

Server Side Includes technology is a great time saver on your website. One of the most common ways to use SSI is to update a large number of pages that contain a particular block of data, without having to update each page individually (for example, to change the citation at the bottom of the page).

To enable SSI, enter the following code in .htaccess:

AddType text/html .shtml
AddHandler server-parsed.shtml

These lines tell .htaccess that .shtml files are valid, and the second line tells the server to check all files that end in .shtml for SSI commands.

However, if there are a large number of .html pages on the server, the extension of which will take a lot of time to change to .shtml, you can use another tactic to check them for SSI commands. The XBitHack parameter is used for this.

Adding this line to the .htaccess file forces Apache to check all html files with the appropriate permissions for Server Side Includes.

To allow a page to use XBitHack, enter:

chmod +x page_name.html

Results

This guide covers only the basic functions of the .htaccess page, which, however, make working with the site much more flexible. If you have any questions or additions about the capabilities of the .htaccess file, please leave a comment.

Tags: ,

The .htaccess file (English hypertext access) is used for simple and convenient configuration of the 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 encoding problems, 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 is not working at the moment. If error 500 Internal Server Error appears, it 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 the following lines to the .htaccess file:

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 server operation, 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), think that the site will no longer work and will never return to it. To show him your separate page instead of a standard error page (incomprehensible to the user), on which there will be, for example, a message that the site is temporarily not working, but will later restore its operation and is definitely worth returning to (the KinoPoisk website displays a message when the servers are overloaded "The Matrix is ​​reloading..." and the corresponding picture). The most common solution is to create your 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 that they look for the necessary information on the site, and not leave 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 a text message that 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 Globals variables:
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 making a request 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 the php.ini file is responsible for PHP settings, 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 numeric 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 - enable/disable 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 the maximum upload file size

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

How to create a .htaccess file for a beginner? The .htaccess file, as a rule, only has an extension for Unix systems. And it benefits sites running an Apache server. Htaccess has a set of rules for a specific site on the server. Which the Apache server executes while the site is running. Thanks to it, you can specify a significant number of useful rules for the site.

Instructions for creating a .htaccess file:

  1. To create this file! It is enough to use any available text editor (for example, Notepad).
  2. Title (.htaccess) - without quotes or anything else.
  3. Save the file.
  4. Then we transfer it to your server (hosting) using an FTP client. Be sure to go to the root directory of the site.
  5. Then you can edit it as you wish. But be sure to update the file version on the server (hosting).

The content of the article:

Features of setting up the .htaccess file and common errors

That's right, this file most often causes a banal server error 500 Internal Server Error. You must edit the file very carefully. And also, follow the following rules:

  1. Always before you start editing the .htaccess file, save a working copy of it.
  2. Never introduce new rules to a production site. An initial check of the file is required.
  3. Encoding is usually UTF -8.
  4. Each rule must be written on a new line.
  5. Those instructions that are not processed by the Apache server are excluded. They immediately cause a server error.
  6. You cannot write multiple instructions on one line. Error 500 will be provided to you.
  7. Be careful! An extra space or character may cause an error.

What effect does the .htaccess file have on the site?

As a rule, thanks to this file, the site can be well optimized for search engines. Here's what it can do:

  1. Setting up a 301 redirect on a website (a common rule). Can be used for necessary tasks.
  2. Site hashing settings on the server side.
  3. Enable gzip compression (short for GNU Zip). Server-side file compression.
  4. Ensure site protection: blocking IP addresses, bans, etc.
  5. Specify the required amount of allocated memory for the site.

When it comes to the best blogging system, WordPress always comes out on top. Although it most often acts as a Content Management System (CMS), its main function remains blog management. Most aspiring developers will likely encounter it in their careers, if they haven't already. One of the interesting topics for such developers could be the .htaccess file that comes with WordPress. In today's guide, we will try to cover this topic by explaining the meaning of the .htaccess file in the WordPress system and showing how to create it.

Before you start this guide, you will need the following:

  • Access to your hosting control panel

What is a .htaccess file?

If you're a new developer, chances are you're not very familiar with the .htaccess file. There is a reason for this, this file is hidden by default and located in the root directory of your site. If, of course, it is there at all, which is not uncommon.

In WordPress, the .htaccess file is not a feature. Any site that is located on an Apache server can use the .htaccess file. The .htaccess itself is a settings file for the server. When your site starts, the server looks for this file and, if it is located in your site's directory, executes it.

The purpose of the .htaccess file is to change certain settings of the Apache server. Therefore, it is quite useful for enabling and disabling certain server functions. For example, it is used to create a redirect from and vice versa. Other uses include changing permissions for specific files, blocking bots, or adding MIME types. It may also be useful for . These features are quite useful when working with WordPress, as you can change the settings to suit your needs.

How to Create a Standard WordPress .htaccess File

When you download and install WordPress on an Apache server, it should already come with a .htaccess file. But since this file is hidden, you must enable showing hidden files on your system. We have a detailed guide on how to. However, in some cases this file may be missing or accidentally deleted. In such a situation, we recommend creating the .htaccess file manually.

The steps below will show you how to create a file in Hostinger File Manager. However, the sequence of actions should not differ much from those on cPanel. You can also create a file on your computer and then upload it using

To create an .htaccess file using , simply navigate to the root directory of your WordPress site. Usually this is a directory public_html. Next, create a text file and name it .htaccess.

Open the file in any text editor. The .htaccess file contains several lines of code, which are standard server settings. In WordPress, .htaccess should look something like this:

# BEGIN WordPress RewriteRule ^index\.php$ – [L] RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule . /index.php [L] # END WordPress

Just copy this code and paste it into the created .htaccess file. Save changes and exit.

Congratulations! You have created your own .htaccess file. Now visit your site and check if everything is working correctly, as incorrect file configuration can lead to the appearance of .

Conclusion

The .htaccess file is required for WordPress to function properly. It can provide several useful features for the server, especially those related to security.

In this guide, you:

  • Learned about the .htaccess settings file and its purpose
  • Learned how to create your own .htaccess file
  • Added the necessary code for the file to work correctly

Now that you have a basic understanding of the important WordPress .htaccess file, you can continue to explore its capabilities to improve your WordPress project.



 

It might be useful to read: