Htaccess redirect and its configuration

.Htaccess files can be located in the root directory of a site (for example, / home / user / sitename /) or its subdirectories. They are used to organize the redirection ("redirect") of visitors from one domain or document on your web server to another. Each .htaccess file contains a set of rules (directives), according to which the web server redirects the user to a particular page.

Many content management systems take the site redirect settings from .htaccess. You can edit the files created by your CMS by introducing new redirection directives, or you can create your own .htaccess files manually.

htaccess redirect

Creating a .htaccess File

The first step in setting up the .htaccess redirect is, in fact, creating the file itself. Your .htaccess should be a plain text file. This means that you need to create it in a text editing program capable of generating plain text (.txt) files.

  • On a Windows computer, you can use Notepad, which is one of the built-in standard programs.
  • On Mac, you can use TextEdit. First you need to open the “Settings” menu in TextEdit and select “Simple Text” in the “New Document” section. After that, you can begin the process of creating a new TextEdit text document for your .htaccess file.
  • On Linux, you can use any of the many text editors available for your distribution - both console (vi, nano) and graphical (for example, gedit).

When saving a document, be sure to name it htaccess.txt. If you save it simply as .htaccess, your computer will hide the file. This is because files starting with a period are considered system files.

Upload .htaccess file to server

For correct redirection via .htaccess, the file must be loaded in the directory on the server for which you want to set redirection settings. This is usually your directory of HTML files (/var/www/vhosts/example.com/httpdocs/), although you can upload it to any subdirectory on your server.

Once the file is uploaded, rename it directly to .htaccess.

At this point, the file may become invisible to your FTP client, as it now has a system file format. Many FTP clients allow you to view hidden files and folders - it is recommended to enable this feature. For instructions on how to enable it, see your client’s documentation.

Checking the operation of .htaccess

The easiest way to check if the web server is processing your .htaccess file is to intentionally damage it.

Edit the .htaccess file so that the first line starts with the word Test:

Test

# Set home page

DirectoryIndex page.html page.txt ...

Now, if you reload the main page of your site, you will see the following error (in the photo below).

htaccess redirect files

If this error appears, then this is actually good - it means the server processes your file and reads the redirection directives from it. If not, make sure that the file and directory in which it is located are readable and change the permissions if necessary.

A bit about the priorities of the redirect .htaccess

.Htaccess rules are recursive. That is, the directives written in the /home/user/sitename_html/.htaccess file will be applied to this directory and its child folders, unless a specific rule is canceled using the directive in the .htaccess file located in child directory.

Thus, the redirect settings through .htaccess set by the file at a higher level are overridden by the settings of files located at lower levels. For example, if you want to enable redirection for most of your site, but disable it for a specific directory, you can create a separate .htaccess with the appropriate settings and upload it only to this directory.

Similarly, lower-level .htaccess files override PHP settings in vhost.conf and php.ini files at higher levels, unless overriding is explicitly prohibited for these files.

Finally, the order of the .htaccess redirect rules in a file may be relevant for certain types of directives. The list of rules is processed sequentially from beginning to end; directives at the beginning of the file will be executed first.

htaccess redirect

Redirect .htaccess: main types

There are various types of redirects that can be performed through .htaccess files. We will analyze them, and consider each type before learning how to use them.

301: permanent redirect

This is the most common type of call forwarding and most likely the one you will most often configure. In a .htaccess 301 file, a page redirect indicates that its old URL (redirected URL) is no longer used.

302: temporary redirect

A 302 redirect indicates that the old page URL is temporarily disabled, but will be restored soon. For Apache, this redirection rule is used by default.

Thus, before setting up the .htaccess redirect, you need to decide if the redirection will be permanent or temporary. For the examples in this article, we will use the 301 redirect.

redirect via htaccess

Redirection Script Examples

Below are the most common .htaccess redirect examples.

In order to use any of them, you need to open the .htaccess file you created with any text editor and add the required code sample to it.

In order for the code to work, the rewrite module (mod_rewrite) must be enabled on the Apache web server. This requires a series of actions depending on your OS.

On Windows, do the following:

  1. Locate and open the .http.conf file . It is located in the directory in which you installed Apache.

  2. Back up http.conf to restore the file if necessary, if you make any mistakes.

  3. Find the line #LoadModule rewrite_module modules / mod_rewrite.so in the file and uncomment it (remove the # sign).

  4. Locate the block enclosed in the <directory> tags and replace it with <directory /> Options All AllowOverride All </directory>.

  5. Find all references to "AllowOverride None" and replace them with "AllowOverride All" everywhere .

  6. Restart your web server and your browser.

On Linux, it is enough to execute in the terminal:

sudo a2enmod rewrite

This command will start the module or give a notification that the module is already running. To trigger new changes, restart Apache with the command in the terminal:

sudo service apache2 restart

htaccess 301 redirect page

Now we can start editing the .htaccess file and study the most common redirection directives.

1. Redirect from one page to another in .htaccess:

Redirect 301 /retiredpage.html http://www.example.com/newpage.html

2. Folder redirection (with all contents):

RedirectMatch 301 ^ / olddir / http://www.yourdomain.com/newdir/

3. Redirecting the page to .htaccess with WWW removal:

Rewriteengine on

RewriteCond% {HTTP_HOST} ^ www \ .sitename \ .com $ [NC]

RewriteRule ^ (. *) $ Http://sitename.com/$1 [L, R = 301]

4. Redirection with the addition of WWW:

Rewriteengine on

RewriteCond% {HTTP_HOST}! ^ Www \ .samplehost \ .com $ [NC]

RewriteRule ^ (. *) $ Http://www.samplehost.com/$1 [L, R = 301]

5. Redirect to another domain in .htaccess (transfer the entire site):

RedirectMatch 301 ^ (. *) $ Http://www.yoursite.com

6 .htaccess-redirect HTML files to PHP files:

RedirectMatch 301 (. *) \. Html $ http: //www.examplesite.com$1.php

7. Redirecting pages with the addition of HTTPS:

RewriteCond% {HTTPS} off

RewriteRule (. *) Https: //% {SERVER_NAME} / $ 1 [R = permanent, L]

8. Replace all uppercase letters in the URL with lowercase:

<IfModule mod_rewrite.c>

RewriteMap lc int: tolower

</IfModule>

This code snippet needs to be added to the httpd.conf of your web server. After that, you need to open the .htaccess file and make:

Rewriteengine on

RewriteCond% {REQUEST_URI} [AZ]

RewriteRule $ {lc:% {REQUEST_URI}} [R = 301, L]

9. Using regular expressions. Redirect rules often contain characters that add up to regular expressions. Thanks to this, the server knows exactly what you want to change in the URL. However, regular expressions can be difficult to understand at a glance. Here are some common elements that you can see and use in your URL rewriting rules, as well as specific examples of their use:

  • ^: start of replaced string;

  • $: end of string to replace.

Example: the regular expression ^ folder1 $ gives a signal to find and replace the text “folder1” inside the link.

  • . : any character that is not a space (for example, a, B, 3);

  • *: indicates that the preceding text can be repeated any number of times;

Example: the regular expression ^ uploads. * $ Allows replacing the text "uploads2009", "uploads2010" and so on;

The regular expression ^. * $ Means "find anything." It is useful if you do not know what the user can enter in the text URL.

  • (): select a piece of text that should be used in the rule as the value of the variable $ 1. This is necessary, for example, to process requests for specific files, which should be the same for both the old and the new version of the URL.

htaccess redirect does not work

Error 404 Not Found

Sometimes it happens that when setting up redirection errors occur. Consider the main reasons why the .htaccess redirect may not work.

Common is the 404 Not Found error that occurs when redirecting. In this case, you need to carefully study the URL generated in the address bar. Does the desired file exist in a new location on the server specified by the redirection rule? You may need to copy files from your old location to a new location, or make the redirection rule wider, so that in the absence of the necessary file, the link redirects to the main page of the site.

If the URL is simply incorrect (for example, http://example.com/folder1//file.html - pay attention to two slashes), you need to revise the redirection rule syntax.

Infinite URL, Timeout, or Loop

If the URL generated during the redirect is too long, or the page does not load for too long, or your browser gives a redirect error message, most likely several redirect rules conflict with each other.

You need to check the entire .htaccess file for redirection rules, which may coincide with other rules. You may also need to check .htaccess files in subdirectories. Please note that FTP will not display .htaccess files if you have not enabled the ability to view hidden files and folders.

You can also include redirects within HTML and PHP pages. Check the page with the problem for internal redirects.

Adding [L] after the redirect rule can help in some cases, because this flag instructs the server to stop trying to redirect the URL after applying the rule.

How to redirect without .htaccess

redirect to another htaccess domain

In conclusion, we’ll look at how to redirect a URL without editing the .htaccess file using the virtual host of the Apache server. Incidentally, this method is simpler than drawing up redirect rules for a page in .htaccess.

Open the vhost configuration file (httpd.conf) with a text editor, which is usually located in the / etc / apache2 / sites / sitename directory.

The selected fragment of the sample file demonstrates redirection:

<VirtualHost *: 80>

ServerName www.mysite.com

ServerAlias ​​www.mysite.com

Redirect / http://mysite.com

</VirtualHost>

The configuration above redirects all requests to a domain without a WWW subdomain.

To redirect all requests to a domain with a WWW subdomain, change the configuration as shown below.

<VirtualHost *: 80>

ServerName anywebsite.com

ServerAlias ​​anywebsite.com

Redirect / http://www.anywebsite.com

</VirtualHost>

Restart Apache and the site will start to redirect correctly. The above method is the simplest and easier to implement than redirecting from one page to another in htaccess.

Source: https://habr.com/ru/post/K13286/


All Articles