• Htaccess 301 redirect from a non-existent page. Mass category replacement

    • Posted by Nikolay Korotkov
    • Date: November 29, 2013 at 09:23

    Hello again!

    Today I will tell you how to set up a 301 redirect. You may have already heard about 301 redirects more than once, but due to the lack of necessity, or perhaps because of the fear of doing something irreparable, you did not attach much importance to this, at first glance, complex abbreviation.

    Many articles have been written on the Internet about setting up 301 redirects. But looking through most of them, beginners may have their brains “exploded.” All these incomprehensible scripts and codes cause confusion for many. In fact, not everything is as complicated as it seems at first glance, and in this article, I will try to convey to everyone as clearly as possible how to set up a 301 redirect.

    Now let's talk about everything in order. What is a 301 redirect? This is a common redirection of the visitor to another page or domain (read about what a domain is and how to register it). I’ll say right away that in this article I won’t look at various scripts and complex codes, I’ll just show a few simple redirection options that any webmaster will know more than enough.

    How to set up 301 redirect? Redirect.htaccess

    We will look at 301 redirects via .htaccess. Htaccess is a utility configuration file that hides a lot of possibilities. Using it, you can deny access to individual directories, specify page encoding, set protection for files and folders, make 301 redirects, etc.

    This is in general terms so that you understand its purpose, but it actually has much more possibilities than you can imagine. At its core, the file has no name and is written as an extension .htaccess with a mandatory dot at the beginning.

    If suddenly this file is not in the root directory of your site, create it yourself. The easiest way to create a .htaccess file is to use the FTP client FileZilla (I wrote about it):

    To do this, go to the root directory of your blog, right-click in the empty field/Create new file/Enter file name/.htaccess/OK. After this, the file will be available for editing. You can open it with any text editor, for example.

    But there are times when the ftp manager hides system files, including .htaccess. Therefore, if you do not find a file in the root directory, do not rush to create it. First, check its availability in hidden files.

    To do this, go to the “Server” tab and check the box next to “Force hidden files”. If in this case you do not find the .htaccess file, then create it.

    In what cases might a 301 redirect be needed?

    Let's start with the most important thing!

    In general, every resource on the Internet should have a 301 redirect. And the most common case when it is simply necessary is a redirection from a domain with a WWW prefix to a domain without it, or vice versa (www is also called a prefix). Now I’ll briefly explain why this happens so that everyone understands what we’re talking about.

    The fact is that for any resource on the network, one of the domain name options (with www or without www) must be the main one. Here is a simple example regarding my blog. Its main domain is http://site, A www.site- is his mirror. The main mirror of the blog is written in the robots.txt file for Yandex in the form of the Host directive.

    If you don’t have a robots.txt file, be sure to study it here, where I described everything in detail. Robots.txt mandatory must be present on every resource. Otherwise, the blog is doomed to failure! In addition to robots.txt, you need to specify the main mirror of the site in Yandex.Webmaster.

    But since it is already indicated in robots.txt, I recommend that you leave everything to the robot’s discretion. To do this, go to the “Indexing Settings/Main Mirror” tab and check the box next to the “At the discretion of the robot” item:

    In order to use this function, you must be registered with Yandex.Webmaster. I wrote about how to do this. Until recently, Google's Webmaster Toolbar included similar function, where the main domain was indicated, but after entering latest changes developers, it disappeared.

    By specifying the main mirror of the site, your resource will be indexed correctly and will not create duplicates. Many newcomers may not have even heard of a site mirror, which is a big omission that causes a lot of troubles in the future, which I will talk about below.

    After all the manipulations done with the mirror, search robots will already determine the main domain themselves. You can even test the redirection, everything should work fine. And we could stop there, but SEO is such a thing that you shouldn’t rely on luck and it’s better to play it safe once again by setting up a redirect.

    As for the www prefix, it should have died out a long time ago. But since there are still many resources on the Internet with the www prefix, it has a place. For search engines http://site And www.site These are two completely different addresses! And users often type the resource address with www into the browser line, so it’s too early for it to die out. Based on this, mirror settings are simply necessary!

    Consequences of incorrect mirror settings

    In fact, there are not so many of them; I have highlighted only two main points. But their weight will make many beginners think seriously...

    1. Everything external links will be distributed between addresses with www and without www, depending on how third-party resources or users link to you. It turns out that your blog will be deprived of some links, which will negatively affect its promotion and traffic. But that's not the worst thing!

    2. Everyone knows perfectly well that search engines are constantly fighting for uniqueness! They hate duplicate content and severely punish sites with the same content. Now imagine a situation where your blog was initially indexed with the www prefix, but as the resource developed, a site without the www prefix gained more popularity (it is mentioned and linked to more often).

    Naturally, you don’t even know about it and continue to develop your resource. Over time it will grow unique content, natural links and comments. Things are going uphill, so how can you not be happy? But here's the problem! Search engines, observing a site without the www prefix, labeled it as not being unique! As a result, it will no longer be indexed, and over time it will completely drop out of the index!

    This will be scary and very offensive! And to avoid such sad situations, 301 redirects were invented.

    Redirection from a domain from www to non-www and vice versa

    How to set up a 301 redirect in this case? It's very simple. Open the .htaccess file and copy the code below into it.

    Redirect from www to non-www:

    RewriteEngine on RewriteCond %(HTTP_HOST) ^www.vashdomen.ru RewriteRule ^(.*)$ http://vashdomen.ru/$1

    and vice versa:

    RewriteEngine On RewriteCond %(HTTP_HOST) ^vashdomen.ru RewriteRule (.*) http://www.vashdomen.ru/$1

    Please note that instead of yourdomain, in both cases you need to specify domain name your blog!

    Save the .htaccess file and move it back to the root directory, replacing the old file. Now, no matter how the user enters the address of your blog into the browser line (at least website, at least www.site, at least http://www.site), it will in any case be redirected to home page.

    Moving from one domain to another

    A similar 301 redirect scheme given above can be used when moving from one domain to another. But still, for clarity, I will give an example. You are moving from a domain sait-1.ru per domain sait-2.com. In this case, write the following in the .htaccess file:

    RewriteEngine On RewriteCond %(HTTP_HOST) sait-1.ru RewriteRule (.*) http://sait-2.com/$1

    Redirect when changing CNC links

    Sometimes it becomes necessary to change CNC links (read about them). Perhaps you have decided to change an entire section (category) on your blog. Or they simply didn’t know anything about CNC, but the blog is already being written and filled with content. In this case, a 301 redirect will come in handy. Moreover, in this situation, all page indicators (previously placed links, weight, PR) will remain at the same level, i.e. will not lose their significance, authority and position!

    Let me give you a simple example. You have decided to change the page title. The old page name was: obo-mne.html, new name ob-avtore.html. In this case, you will need to write the following construction in the .htaccess file:

    Redirect for affiliate programs

    Let's say you decide to redirect the user to a page with affiliate program. The affiliate code looks like this: http://www.partnerka.ru/?ref=35677. Having seen such a link, most users will not click on it, knowing in advance about your intentions.

    In order for the link to take on an attractive appearance, you need to create separate page, for example dlya-partnerov.html, from which the user will be redirected to the page with the affiliate program. Now all that remains is to place a link to the page vashdomen.ru/dlya-partnerov.html, and write the following in the .htaccess file:

    redirect 301 dlya-partnerov.html http://www.partnerka.ru/?ref=35677

    But personally, for such purposes, I prefer to use the simple script that I talked about (method No. 3).

    That's probably all. Now you know how to set up a 301 redirect and you shouldn’t have any problems with it. I showed you the simplest version of a 301 redirect via .htaccess, which every webmaster should know about. Well, the last thing I want to say is always check the redirects for functionality. That's all, bye everyone!

    How do you like the article? Do you use 301 redirects? Perhaps you know of easier redirection methods? I'm waiting for your comments!

    Did you like the article? Share with your friends!

    A book for every commentator!

    The book includes detailed description the most effective methods promoting your resource!


    60 comments

    1. 29 November 2013 15:20

      I read it and didn’t understand a thing... For people like me, there is only one thing left to do, find a person, tell him to set up a 301 redirect and trust that he did everything =))))

      So it still wasn’t possible to explain it well...

      No, no, everything is very sensibly and clearly written - thank you!

      It’s just that many are lazy to follow the recommendations, many do not attach serious importance to their projects, and so they do not bring them to fruition. And on some issues there are conflicting recommendations. So, in robots.txt it is recommended to place the indication about the main mirror of the site at the beginning of the file, then there is an empty line, then the rest of the data. I don’t dare judge how true this is, but the author of this recommendation actively insists on this order of filling out robots.txt, and where can beginners figure it out?

      Why do they get lazy right away? If your brain is sharpened to sit and pick out codes, then others do not have this gift and in order not to fail everything, they either don’t do it, or, as in my case, I turn to a specialist and he will set everything up for me... So. ..

      Namesake, we’re not talking about you!

      You are a specialist in YOUR business, to whom it is strongly recommended to delegate routine technical work.

      So, be creative, and don’t bother yourself with what distracts you from your main task.

      The point is that there are many people who make websites “what would be”, or “I’ll finish it later”. So I haven’t fully implemented even what I already know: my main work, other things are getting in the way... Yes, there will always be plenty of reasons not to do it. But this is the biggest mistake when a person has not done one thing, but is already looking for another. Accumulated and not applied knowledge is useless, alas.

    2. November 30, 2013 11:12
    3. 30 November 2013 16:02
    4. Anna November 30, 2013 19:59

      I finally understood what a redirect is, especially with examples, everything is well explained. And in general, I appreciate Nikolai’s articles because they write in clear language what it is, why it is needed and how to bring it to life.

      On the topic of this article, there is only one question left: if we enter a domain name with or without www and get to the main page of the site, then the redirect is configured and there is no need to enter anything, or in any case you need to write the code specified in the article in the .htaccess file, if it is there are we not watching?

      If the redirection works correctly, then you don’t have to write anything in the .htaccess file. But personally, just in case, I still registered a redirect in .htaccess, it won’t make it any worse.

      It turns out that whoever does not write from www still ends up on the site?

      I just thought that this was the functionality of the CMS itself, and never thought about it...

      Alexander

      Right! For these purposes, a 301 redirect is configured. This is not included in the CMS itself.

      How will I know if this redirection stops working? Everything is great now!

    5. Elena February 1, 2014 22:55

      I wrote something in a comment, but didn’t go - it’s a pity. that one was longer.

      In general, I read and read and nothing came to me.

      Tell me how to redirect each page?

      After all, you can later, when it is indexed on a new site, remove the articles from the old one and remove them on the new site (each link has a redirect). And what will happen in general - the search engines will be shocked and will delete everything, or will index it again.

      Show an example on your website of one page on another - how to put it correctly, otherwise I did (I found the information on the internet) and nothing worked out.

      Redirect 301 /old page.html site.com/new page.html

      Redirect permanent /old page.html site.com/new page.com/

      In your case, a redirect when changing the CNC links, described by me in one of the paragraphs of this article, is suitable. Moreover, as you correctly noted, after re-indexing the pages, it will be possible to remove articles from the old site and remove redirects. Search engines will react normally to changes of this kind. They will perceive this as a normal redirection.

      And at your request, I’m showing a simple example on my blog. Let's say I want to redirect visitors from the All Blog Articles page to the My Courses page. In this case, I write the construction as follows:

      redirect 301 vse-stati-bloga.html site/moi-kursy

    6. Pavel March 25, 2014 11:37 pm

      And in my .htacces file only this code is written:

      # BEGIN WordPress

      RewriteEngine On

      RewriteRule. /index.php [L]

      what should I change? Is the file compiled incorrectly?

    7. April 29, 2014 10:39

      Nikolay, good afternoon!

      I’m translating a 15-page business card to a self-written website on WP. The site is 3 months old, but there are already 10 users, a small thematic traffic, so I don’t want to destroy everything. A new website on wp is installed and configured, the website pages hang out on the server in parallel, but are not visible to the user.

      As far as I understand, a redirect for CNC is suitable for me, after setting it up it will be possible to either transfer the old content, or write a similar new one and the handwritten page can be removed from the server or what?

      Please tell me, testing a redirect is just going to the old address and seeing that everything opens correctly on a new page? Does that mean search engines will see it in the same light?

      Thank you very much in advance!

      Hello, Irina!

      You understand everything correctly... A redirect for CNC is suitable in your case. If the old pages were indexed by search engines, then transferring the old content to a new domain without a redirect will be considered a duplicate; it is better to use a redirect. And testing it is very simple. If, when you enter the address of the old page, the browser redirects you to the new domain, then the redirect works as it should and search engines will soon re-index the content. Then it will be possible to delete old dangling pages from the server without problems.

      Nikolay, thank you for the quick response!

      Only the old domain remains, I just switch from the handwritten version to wp and that’s it.

      I checked the server response code - there was a surprise waiting for me

      Instead of 200OK - 301 redirects. Opened htaccess. and what do you think? There seems to be a standard set:

      # BEGIN WordPress

      RewriteEngine On

      RewriteRule ^index\.php$ - [L]

      RewriteCond %(REQUEST_FILENAME) !-f

      RewriteCond %(REQUEST_FILENAME) !-d

      RewriteRule. /index.php [L]

      Tell me, can I set up a redirect via 301 without paying attention to the server’s response?

      Thanks in advance!

      Status code 301 means that the requested page has permanently moved to a new location. The standard rule in the .htaccess file is precisely responsible for the redirect. So that the server’s response in this case is shown correctly, in the future the redirect can be removed and old pages can be deleted from the server.

      Yes, I understood, but it’s not entirely clear where this redirect came from, because I didn’t set it and how it was implemented if htaccess. it’s not there... Apparently, it was somehow automatically added by the system after I created an index page in wp and deleted the old handwritten one. Now I will register a redirect to the remaining pages in htacess manually.

      Thank you for the article.

      Nikolay, I also wanted to ask a question based on the speed of response, but I don’t know where. For some reason, site search doesn’t work for me, but I don’t want to spam the topic.

      Sorry, I forgot to specify where the line goes

      redirect 301 obo-mne.html yourdomain/ob-avtore

      attach it to a ready-made structure

      # BEGIN WordPress

      RewriteEngine On

      RewriteRule ^index\.php$ - [L]

      RewriteCond %(REQUEST_FILENAME) !-f

      RewriteCond %(REQUEST_FILENAME) !-d

      RewriteRule. /index.php [L]

    8. Irina April 29, 2014 20:26
    9. Irina 19 May 2014 22:34

      Nikolay good evening!

      We need your help again!

      In the last update, Yandex chose site.ru with www as the main mirror (and since it was without www, tits was reset to zero!)

      All hands didn’t get around to it, but now it will have to... The problem is that I recently transferred a handwritten site to WordPress and those pages on which there were links, I have already redirected with 301 redirects to new addresses, my htaccess now looks like this:

      redirect 301 /file.html site.ru/new category name/

      # BEGIN WordPress

      RewriteEngine On

      RewriteRule ^index\.php$ - [L]

      RewriteCond %(REQUEST_FILENAME) !-f

      RewriteCond %(REQUEST_FILENAME) !-d

      RewriteRule. /index.php [L]

      I tried to attach the redirection both before the line # END WordPress and at the very top of the file

      - gives a redirection error, writes that it will never end...

    Many have heard it more than once. But due to the lack of need for it, and also because of the fear of doing something wrong, they did not attach importance to such a procedure. This article will discuss in detail how to set up a 301 redirect.

    You can find dozens of articles and information materials about setting it up. But after viewing many of them, novice computer users and webmasters may have difficulty understanding the basics of configuration. Numerous codes and scripts provided in online sources of information are mostly misunderstood. In reality, everything is much simpler, and this article will serve good leadership How to set up a 301 redirect.

    What is a 301 redirect?

    Let's figure it out in order. First of all, let's define a 301 redirect. It is understood as the simplest redirection of a guest of an Internet resource (site) to another page on the Internet or a domain name. Let’s make a reservation right away that this article will not consider any tricky scripts or overly complex code, but will show several simple options redirects which is enough basic knowledge on this topic for any webmaster.

    Tool for - .htaccess file

    Let's consider such a convenient tool as .htaccess. Doing a 301 redirect through it is very convenient and simple. Htaccess is essentially a special service configuration file that contains a lot of functionality and many possibilities. Using it, you can set a ban on access to any directories on the site server, specify the encoding of pages, set protection for folders and files, perform 301 redirects and some other actions.

    This is a description of the capabilities of this file in general terms. In fact, its functionality is even more advanced. The file has no name and is written as .htaccess. The period at the very beginning is mandatory.

    Procedure for creating a .htaccess file

    If this file is not in the root folder of the site, you can very easily create it yourself. One of the most quick ways creation - using an FTP client. The most convenient of them is FileZilla.

    To create, you need to go to the root directory of your Internet project - click on empty space right button computer mouse- select "Create a new file" - enter the name.htaccess - click OK. After these steps, the created file can be edited. It can be opened with any text editor.

    But it also happens when FTP clients hide some system files, including .htaccess. Therefore, if this file was not found in the root folder, there is no need to rush to create it. First of all, check for its presence in hidden files. To do this, go to the “Server” tab and check the box to force the display of hidden files.

    So, if the .htaccess file has been created or found, it will be easy to create a 301 redirect using it. However, first of all you need to decide what it is needed for.

    The most popular case when a 301 redirect can be useful

    According to the recommendations of leading webmasters, every resource on the Internet should have 301 redirects. And the most popular case when it is very necessary is a redirection from a domain that has a prefix with www to a domain without it and vice versa.

    This is explained by the fact that for any site on the Internet, only one type of domain name with or without www can be the main one. Another option will be a mirror of the site. The main mirror of an Internet resource is signed in the robots.txt file using the Host directive. In addition to this file, the main domain option should be specified in Yandex.Webmaster. Many search engines are very accepting of tools such as 301 redirects. Yandex is no exception to this.

    When you specify the main mirror of an Internet resource, your site will be indexed correctly and will not create unnecessary takes. Many newbie webmasters have never heard of mirror sites, which is a very big mistake that will cause major troubles in the future.

    The value of setting up site mirrors

    After all the actions taken with the mirror, search engines will determine the main domain automatically. You can even easily check the redirect, everything will work fine. We could stop at these steps, but the best way to optimize an Internet resource for SEO would be to additionally configure the redirect.

    The www prefix itself in the designation should have gone into oblivion a long time ago. But nevertheless, there are still many resources on the Internet with www in the name. For search engines, domains with and without www are two different addresses. And many users, when searching for a specific Internet project, type www into the address bar. Therefore, this prefix still exists. Based on this fact, adjusting the mirrors is a necessary action. And the guide on how to set up a 301 redirect is also a must-read so that your Internet project is successfully indexed in search engines.

    Consequences of incorrect mirror settings

    In order to appreciate the full significance of 301 redirects and the correct configuration of mirrors, we will highlight the detrimental consequences of their incorrect operation. There are not many of them, only two. But the weight of each point is very great.

    They will be divided between domains with and without www, directly depending on how other users and sites will link to your resource. This means that your Internet project will lose some of its links, which will negatively affect its traffic and place in search results. However, this is not the main problem.

    Many webmasters understand that search engines are constantly fighting for the uniqueness of the content of Internet resources. They have a very negative attitude towards duplication of information and quite seriously punish sites with similar content, up to their complete blocking in search results. Now let's outline the following situation: your resource was indexed with the www prefix from the very beginning, but over time a domain without www received larger number attendance and popularity (it was referenced more often and mentioned more often).

    You know nothing about this and continue to develop your project. Over time, it is filled with unique content, many links and comments. Search engines, monitoring a resource without the www prefix, sent it to a ban for non-unique content. Over time, it will completely stop being indexed.

    In order to avoid this situation, there is a .htaccess file. The 301 redirect written in it can solve the problem of dividing a resource into domains with and without www.

    Redirect from domain www to without prefix and vice versa

    How to set up a redirect in this case. Everything is simple here. You need to open the .htaccess file and write the script below into it.

    Redirect from domain www to without it:

    RewriteEngine on
    RewriteCond %(HTTP_HOST) ^www.moydomen.com
    RewriteRule ^(.*)$ http://moydomen.com/$1 .

    And in another way:

    RewriteEngine On
    RewriteCond %(HTTP_HOST) ^moydomain.com
    RewriteRule (.*) http://www.moydomen.com/$1.

    You need to take into account that instead of moydomain.com you must indicate the address of your Internet resource in both cases!

    You should save the .htaccess file and move it to the root folder and then replace the previous file. Now, whenever a visitor enters a site address (whether with or without http, with or without www), he will in all cases be redirected to the main page. We looked at how to set up a 301 redirect to from www without www. Let's now look at the other ways to use it.

    Transition from one Internet project domain to another

    A similar redirect scheme, which is given above, should be used when moving from one domain of an Internet project to another. To demonstrate, let's give an example. Let's say you should move from the domain moysait-1.com to moysait-2.com. In this case, you should write the following code in the .htaccess file:

    RewriteEngine On
    RewriteCond %(HTTP_HOST) moysait-1.com
    RewriteRule (.*) http://moysait-2.com/$1.

    Changing CNC links and redirecting at the same time

    From time to time there is a need to change. It is quite possible that a situation has arisen that it was decided to change the entire section on your resource. Or the site owner knew nothing about CNC links, and the blog already existed and was filled with materials. In this case, redirection can help. How to set up a 301 redirect for this case? It is important that in this state of affairs, all page indicators (links, their weight in search results) will remain the same.

    Let's give a simple example. It was decided to change the name of the page from moya_infa.html to obo_mne.html. In this case, you need to write the code in .htaccess: redirect 301 moya_infa.html http://www.moydomen.com/obo_mne.html.

    A 301 redirect from page to page is done in a similar way.

    Redirection when changing file extension

    Let's give another example. The webmaster needs to change the extension of the moya_stranichka.html file to moya_stranichka.php. Similar to the previous point, we write the following code in .htaccess: redirect 301 moya_stranichka.html http://www.moydomen.com/moya_stranichka.php.

    Redirect for affiliate programs

    For example, you need to redirect a site visitor to a page with an affiliate program. The affiliate program link itself looks like www.partner.com/?ref=16011. Having noticed such a link, many resource visitors will not click on it, having guessed your intentions in advance.

    To give the link the proper appearance, you need to create a separate page, like the example dlya_druzei.html, from which you will redirect to the page with the affiliate program. All that remains is to edit the .htaccess file: redirect 301 dlya_druzei.html http://www.partner.com/?ref=16011.

    How to perform a 301 redirect in CMS Joomla

    Many Internet users have probably seen a page with a 404 error. Joomla engine There are already several built-in methods for redirecting from page to page. However, they don't always work. And are very difficult to understand regular user. This is where the 301 redirect comes to the rescue. Joomla has a standard .htaccess file with which you can perform all the manipulations described above.

    Let's set up redirections for all pages of your Internet project. First of all, you need to find the htaccess.txt file in the directory and give it the correct name.htaccess. After this, in the admin panel you should set the redirection settings to enable CNC (SEF) and check the URL redirection box.

    Then you should open the .htaccess file and write the rules for the required redirections in it.

    Redirect using PHP

    If for some reason access to the .htaccess file does not exist or is closed, there is a way to do a 301 redirect differently. PHP will help with this.

    In order to redirect from domain to domain while saving all parameters, you need to create a file with the extension .php in any text editor, call it index and copy the following script there:

    if ($ref!="") $ref="?".$ref;header("HTTP/1.1 301 Moved Permanently");

    header("Location: http://moydomain.ru/".$ref);

    Here moydomain.ru is the domain to which the redirect is made. The resulting file must be uploaded to the server in the main directory of the site.
    In order to redirect from page to page within the same domain or different ones, you need to insert the following before the main code of the transferred page:

    header("HTTP/1.1 301 Moved Permanently");

    header("Location: http://www.moydomain.ru/moycategory/moypage.htm");

    As a result, www.moydomain.ru/moycategory/moypage.htm is the new page to which the redirect is made.

    It is important to take into account that the page into which the above script is inserted must have the .php extension at the end of its name. Otherwise, you will have to use a redirect via .htaccess.

    Now, after studying the article, any webmaster will know how to set up a 301 redirect, what it is and how it is useful. This shows the simplest use cases for redirects. However, any website and blog owners need to have an idea about them. And it is worth taking into account that it is important not only to configure the redirection correctly, but also to check it for correct operation.

    As you can see, redirections can be created not only using the .htaccess file, but also through the standard capabilities of many CMSs and using PHP scripts.

    The rules are given for the Apache server. In the rules: %(QUERY_STRING) - denotes the fragment of the URL after the question mark (setting the values ​​of CGI parameters). The triggering of a particular redirect rule is determined by whether the URL of the page falls under this rule or not. About the meaning of certain designations (^, $, NC, etc.).

    Below are the most used rules for setting up the .htaccess file for 301 redirects. It is better to place all the rules after two lines:

    Options +FollowSymLinks RewriteEngine On RewriteCond %(HTTP_HOST) ^site\.ru$ RewriteRule ^(.*)$ http://www.site.ru/$1 RewriteCond %(HTTP_HOST) ^www.site\.ru$ RewriteRule ^(.*)$ http://site.ru/$1 Redirect 301 /was.php http://www.site.ru/new.php

    In this case, the new address must be specified in full with http and the domain name.

    RewriteRule ^dir /dir-new/$1

    Let's say the page address looks like: http://www.site.ru/dir/index.php?IBLOCK_ID=1&SECTION_ID=111 , then to set up a 301 redirect to a new address, you need to use the following rule:

    RewriteCond %(QUERY_STRING) ^IBLOCK_ID=1&SECTION_ID=111$ RewriteRule ^dir/index\.php$ /new/sef/?

    If one (or more) of the GET parameters is not specified or can have an arbitrary value (in our example it is SECTION_ID), you can use the following code:

    RewriteCond %(QUERY_STRING) ^IBLOCK_ID=1&SECTION_ID=(.*)$ RewriteRule ^dir/index\.php$ /new/sef/?

    If you want to set up redirection only for the address http://www.site.ru/dir/, but at the same time so that the page http://www.site.ru/dir/index.php?IBLOCK_ID=1 opens at the old address, you need use the special character $ in the rule.

    RewriteRule ^dir/$ http://www.site.ru/new-dir/

    For domains in the Russian Federation zone, the same rules apply, but all Cyrillic characters must be replaced with an alternative code (it is in Latin). In particular, the zone.рф itself is converted into.xn--p1ai.

    RewriteCond %(HTTP_HOST) ^old-site\.ru$ RewriteRule ^(.*)$ http://www.site.ru/$1

    And for a domain in the Russian Federation zone:

    RewriteCond %(HTTP_HOST) ^xn-...\.xn--p1ai$ RewriteRule ^(.*)$ http://www.site.ru/$1 RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_URI) !\..(1,10)$ RewriteCond %(REQUEST_URI) !(.*)/$ RewriteRule ^(.*)$ http://www.site. ru/$1/ RewriteCond %(REQUEST_FILENAME) !-d RewriteCond %(REQUEST_URI) ^(.+)/$ RewriteRule ^(.+)/$ http://www.site.ru/$1 RewriteCond %(HTTP_HOST) ^si-te\.ru$ RewriteRule ^(.*)$ http://www.site.ru/si-te/ RewriteRule ^bitrix/ /bitrix/admin/ RewriteRule ^(.*)$ http://www.newsite.ru/new/ RewriteRule ^dir(.*)$ /new-file.php RewriteRule ^dir/no-file.html /no-file-new.html RewriteRule ^dir(.*)$ /all.php RedirectMatch 301 (.*)\.html$ http://www.new-site.ru$1.php

    Specifies the loading order of the index file types located at the root of the directory.

    DirectoryIndex index.html index.php index.htm index.shtml RewriteCond %(THE_REQUEST) ^(3,9)\ /index\.php\ HTTP/ RewriteRule ^index\.php$ http://www.site.ru/ RewriteCond %(HTTP_HOST) ^test.site.ru$ RewriteRule ^(.*)$ http://site.ru%(REQUEST_URI) RewriteRule [^abc]/unique-file.html /unique-file.html

    The code allows you to set a 301 redirect from all folders like http://site.ruuniqe-file.html to one file in the root /unique-file.html. It can be useful when redesigning a site and changing links.

    RewriteRule ^testovyi/test/?$ /studio/news/detail.php?ID=230354&PAGEN_2=11

    The code allows you to create a copy of the page with the relative address /studio/news/detail.php?ID=230354&PAGEN_2=11 at /testovyi/test/

    Attention, it is important that the server response code for a 404 error is exactly 404. The path to the file is indicated using the following line:

    ErrorDocument 404 /404-for-me.php RewriteCond %(HTTP_HOST) ^(+)\.site\.com$ RewriteRule ^(.*) http://site.com/$1 RewriteCond %(HTTP_HOST) ^(+)\.site\.com$ RewriteCond %(HTTP_HOST) !=one.site.com RewriteRule ^(.*) http://site.com/$1

    All rules are executed in the direct order they appear in the .htaccess file, and the rule written later will be executed later.

    For sites that do not use an Apache server, similar 301 redirects can be easily configured using PHP:

    It is optimal to configure all redirects immediately to the final page (without intermediate redirects, in one step), this improves their perception by search engines and users.

    RewriteCond %(HTTP_USER_AGENT) (iPad|ipad|iphone|iPhone|ipod|iPod|android|midp|j2me|symbian|series\ 60|symbos|windows\ mobile|windows\ ce|ppc|smartphone|blackberry|mtk|bada| windows\phone)

    RewriteRule (.*) http://mobile.site.ru/

    RewriteCond %(HTTP_USER_AGENT) ! (accoona|ia_archiver|antabot|ask\ jeeves|baidu|dcpbot |eltaindexer|feedfetcher|gamespy|gigabot|googlebot |gsa-crawler|grub-client|gulper|slurp|mihalism|msnbot|worldindexer |ooyyo|pagebull|scooter|w3c_validator |jigsaw|webalta|yahoofeedseeker |yahoo!\ slurp|mmcrawler|yandexbot|yandeximages |yandexvideo|yandexmedia|yandexblogs|yandexaddurl|yandexfavicons |yandexdirect|yandexmetrika|yandexcatalog|yandexnews |yandeximageresizer)

    RewriteRule (.*) http://no-search.site.ru/

    Redirection from www.site.ru/component/content/?view=featured to www.site.ru/

    RewriteCond %(QUERY_STRING) ^view=featured$ RewriteRule ^component/content/?$ /?

    RewriteCond %(QUERY_STRING) ^idc=4&marea=6$ RewriteRule ^index\.php$ /? . - A dot replaces an arbitrary character. - denotes a list of characters matching the letters a, b, or c. [^abc] - a list of characters that are not included in the specified range. Matches any character except a, b, or c. * - means that the preceding character can be repeated (0 or more times). * - the command will find consecutive characters from a given set. [^abc]* - exactly the opposite. .* - replaces absolutely any character set. ".*" - will find all substrings between quotes. ^ - the beginning of the line (if used at the beginning of the expression). $ - denotes the end of the line. \w - letter, number or underscore _. \d - replaces any number. \D - replaces any character, but not a number. - replaces any number. - any letter from a to z (the entire Latin character set) in lowercase. - any letter from A to Z in UPPER case. - any letter from a to Z in any case. - the same. RewriteRule(.*) $1?

    Place after: RewriteBase /

    Reminder on symbols and designations used

    The RewriteCond line is the condition for executing the RewriteRule rule. If the condition is met, then the redirect is triggered. Rules can be specified using regular expressions.
    Special characters used in the rules and their meanings.

    ^ - special character at the beginning of the line;
    $ - special character end of line;
    ! - special negation character;
    . - dot, replaces any character, but only one;
    () - grouping;
    \ is an “escaping” slash; the next character after it is considered a regular character, not a special character.

    Modifiers are used after regular, special characters or their groups and allow you to expand the capabilities of templates for triggering rules.

    The symbol is repeated 0 or 1 time.
    + - repeated from 1 to 65536 times.
    * - repeated from 0 to 65536 times.

    Flags that specify additional options for the rule to use. Listed in square brackets separated by commas, say or .

    NC - NoCase flag, which disables character case checking when the rule is triggered.
    R - Redirect flag, performs the process of stopping the URL change and returns the result. The most commonly used value is R=301, but others are possible for temporary redirections (302, MOVED TEMPORARY).
    L - Last flag, stops the formation of the URL and the line is considered final.

    • Redirect 301 – theory and practice of redirection, setup and rules of use

    UPD:

    RewriteCond %(SERVER_PORT) !^443$ RewriteRule .* https://%(SERVER_NAME)%(REQUEST_URI)

    RewriteCond %(SERVER_PORT) ^443$ RewriteCond %(HTTPS) =on RewriteRule ^(.*)$ http://your_site.com/$1

    Hello friends. Today I would like to discuss a very hackneyed, but always relevant topic - this is 301 Redirect (Permanent Redirect 301) - in the SEO community, and without formalities, this is exactly what is meant by the word “redirect”. Technically, this is the server’s response to a request to it; this response has a code of 301, indicating that the address of the request has been changed permanently (moved permanently). As a result of all these cunning machinations, we should receive some new final address.

    I believe you don't need these technical aspects, and therefore I want to talk about applied things - when and in what situations it is better to use a redirect, how and with what commands you can configure redirection rules, etc. We will also consider tools and services with which you can check the correctness of redirects.

    Since the post turned out to be very long, I decided to make table of contents for your convenience:

    When SHOULD you do a 301 redirect?

    First of all, a redirect is used when a page (a group of pages or an entire section) has changed its address- most often this happens when changing the structure of the site, renaming the main part of the url, or changing the principle of forming addresses (in other words, CNC). Unfortunately, not everyone thinks about this when they change something on the site, and as a result there are a lot of duplicates, which leads to loss of positions or even the imposition of sanctions by search engines. In my work, I very often encounter such situations, and it costs a lot of nerves to correct everything and neutralize the consequences. On my own behalf, I can recommend that before any work on changing the type of CNC or altering the structure, make a plan of the current structure of the site, all its sections and examples of end pages. All this will need to be checked after the work is completed, so that when we go to the old address we get to the new one, and the server gives a redirect with code 301 (not 302).

    The next common use of 301 redirects is changing the site address or gluing mirrors together. If you decide to change the website address in connection with the rebranding of the company or registered a new, more beautiful and shorter domain to indicate it on printed promotional products, it is very important that when accessing the address on the old domain, the user ends up on the same page (and not on home page), but on a new domain. As for promotional sites, they usually consist of one or two pages, links from which lead to the main site, or when you go to the promotional site, a redirect immediately occurs to special page main site. Sometimes, when creating a website, several domains are registered at once, for example, due to the ambiguous spelling of the company name in Latin. To ensure that when intuitively typing an address, the user gets to the right place, and several domains are registered, it is very important that 301 redirects occur from all “auxiliary” domains to one main address. Under no circumstances should the same website be accessible to all addresses.

    And also about mirrors - it may happen that your site will be available at the addresses http://www.site.ru, http://site.ru and https://site.ru(the latter is rare, but it happens) - these are all classic mistakes that should not be made, and 301 redirects are involved in solving them. Just as in the case of different website addresses, you need to decide on the main mirror (with www or without www) and set up redirects to the main mirror. Of course, search engines are not stupid and in such situations they often cope on their own, and you can also help them by doing correct settings in webmaster panels and in robots.txt (for Yandex, Host directive). But SEO is a delicate matter, and I would not rely on luck, but use a proven method!

    Sometimes a very unpleasant situation occurs when a copy of the site is accessible not only by entering the domain name in the address bar, but also the server IP address. This situation is unlikely to happen on shared hosting, but if you have a dedicated server, it can easily happen. This may be the reason for incorrect server configuration - disabling access when accessing an IP address will help solve the problem, but the best solution here is a 301 redirect at the web server level (Apache or Nginx). A couple of months ago I had just such a situation - I had a dedicated server on which some of the sites hung, but for one of the sites I decided to take another separate server. I transferred the site, everything worked like clockwork, and then one day I came across a clone of my site in Google results - shock, panic - it turned out that this was the IP address of my new server and, of course, my site lives on it, and when contacted, the server gives a response 200 OK, and Google has fully indexed it. There was no such problem on the previous server; a 301 redirect from the IP to the domain specified as the main one for this IP was initially configured. Now I have learned from bitter experience and always check such things - be aware and you, do not repeat the mistakes. The problem was solved by adding a redirect to the main domain to the nginx web server configs; I will show an example of the code in the practical part of the post below.

    A situation similar to the previous one - when a copy of the site is located and accessible through a service test domain, for example, like site.hosting.ru. Such cases also occur in my practice, and, unlike the previous case, this is typical for virtual hosting. Why does this exist? For example, you have not yet purchased a domain, or you are transferring a site from one hosting to another, but the NS servers for the domain have not been changed, or the DNS records from the provider have not yet been updated. In such situations, they make test addresses, where you can configure and install everything before redirecting the site address to new hosting. And some hosters sin by not blocking access to such technical addresses and not even prohibiting their indexing. If you have this unpleasant situation, then you should try to register a 301 redirect from the technical address to the main one in the .htaccess file.

    And, of course, 301 redirects really like to use the right SEOs to combat various duplicate pages. Why only the right SEOs? Yes, because the wrong people entered the client’s website and, which is quite likely, began to buy links without even visiting the site - alas, this is not uncommon. I am periodically approached by customers who want to check the integrity of their contractors/employees who are responsible for optimizing and promoting the site, how well the work is going - - and so far it has never happened that I have not found errors or shortcomings on the sites. So, keep in mind - I'm always happy to help you. Let's return to the duplicates - I believe that instead of blocking duplicates from indexing, it is necessary to redirect to the main address, and this is not so interesting. Of course, there are a lot of cases when takes are forced, and then you can’t do without canonization, but if you have the opportunity to make a redirect, be sure to do it. Frequent cases of duplicates that must always be checked: addresses with and without a slash at the end, addresses with parameters and labels - I will tell you how to solve this below.

    When can you do a 301 redirect?

    You can't write much in this section, but I'll try. I really hope that after reading you will add a couple of ideas to me in the comments.

    Redirect 301 can be used as a server response instead of a 404 error Not Found – in other words, the user, following an incorrect link or a non-existent page, will not see a message saying, “Sorry, this page no longer exists,” but will be transferred to another existing page. This is a very controversial point among experts, and therefore I do not impose my opinion on anyone. But I prefer to use a redirect instead of a 404 error, and there are several options for the development of events... Look, there are 2 categories of 404 errors: the first is classic, when the page has actually been deleted, the second is when the error appears due to crooked external links. In the first case, you probably shouldn’t do a redirect, but leave the 404 error as it is. But in the second case, you should take care of a redirect to the correct URL, if it can be restored from a broken link, or a redirect to the main page (or category).

    When NOT to do a 301 redirect

    A few words about when a redirect can harm you, and therefore it should not be used in the following situations.

    The most important thing is to avoid making mistakes, you should not get involved with redirects if you are not 100% sure of what you are doing or doubt something. Take this as friendly advice :)

    Permanent redirect should not be used for temporary solutions, it's obvious from its name - to temporarily move, use 302 Moved Temporarily. In this case, the pages will not be glued together and the page with the redirect can be restored at any time.

    If there are problems with your domain, for example, filters, bans, etc., and you decide to change the site address(domain), then you shouldn’t do a 301 redirect from the old domain to the new one - as a result, you will “glue” all the problems of the old one to the new domain. That is, in the end nothing will change. Yes, for some time there was a solution to get out of the Google Penguin filter using a full 301 redirect from the old domain to the new one. Indeed, all positions were restored to the level before the sanctions, and this seemed to be a panacea for the evil Penguin, but with the next update of the algorithm, this feature was taken into account and the new domain also fell under the filter, as a result, nothing improved after the domain change. If you have already decided to change the domain, then you can try to transfer all the content to the new domain, and delete it on the old one and put up a stub with a message about the move, or even better, start all over from scratch.

    There are many ways to make a 301 redirect: through htaccess, php, javascript, server settings, etc. - so you shouldn’t try to use all methods at once, the likelihood of “disagreements” between in different ways and you can, for example, get an infinite cyclic redirection.

    When you are working with a complex site structure or redesigning a large portal, multiple redirects or long chains often occur. This means that the redirect occurs not in one step, but in two or more - this is a bad situation and should be avoided if possible. When following such a link, a search robot, having received several redirects in a row, may think that it is being deceived and stop following further and stop taking links into account altogether. Here's an example from my practice: I once came across a site for an audit with such an unexpected chain:

    http://site.ru/tax/term/30 ->
    http://www.site.ru/tax/term/30 ->
    http://www.site.ru/tax/term/30/ ->
    http://www.site.hosting.ru/404.php ->
    http://www.site.ru/404.php

    And in the end, the page http://www.site.ru/404.php, which should give a 404 error, gives a 200 OK response. This even blew my mind, but imagine what a search robot would think if it got into such a carousel! Not only did three different domains participate in the chain, but the error page also says that it is not an error and should be indexed.

    If possible, strive for the absence of redirects within the site– if external links to a site cannot be corrected and a redirect is inevitable, then internal links should be corrected. This may not affect the quality of indexing and ranking, but you can’t be sure, and therefore it’s better to avoid such controversial situations. A wonderful one will help you in tracking internal redirects and generally errors within the site.

    When creating redirect rules in .htaccess, exclude the real addresses of directories and files on the server and monitor the selection. The situation for a site that I once got audited was that in the fight against duplicate category pages with and without a slash at the end, the webmaster overdid it a little and, on the contrary, only aggravated the problem. Not only did the rewriting rules affect real js scripts and css style files, causing them to stop working correctly, but also some pages received an unnecessary slash at the end and duplicates appeared. Friends, carefully ensure that the rules you create apply only to the group of addresses with which you are working, and limit all others.

    To search for problematic pages and their addresses that you need to get rid of, use the capabilities of webmaster panels from Yandex and Google. For Yandex Webmaster: Select a site -> Site indexing -> Excluded pages. For Google Webmaster: Select site –> Optimization –> HTML Optimization; And also: Select the site -> Configuration -> URL parameters.

    Features of indexing and re-indexing of redirects in Yandex and Google. When you struggle with duplicates and problematic addresses, of course, you will wait for errors to be removed from the webmaster’s panels; there are some features here. With Google, everything is simple - you set up redirects, the changes will be indexed within 2 weeks, during the same time errors will begin to disappear from the webmaster’s panel, usually after a month all errors disappear. With Yandex, there is a subtlety, and this is the following - after setting up redirects, you can wait forever for errors to disappear from the panel. I once waited for six months until I wrote to support, where they informed me that in addition to the redirect, it is necessary to additionally close problematic pages in robots.txt and only then will they disappear from the webmaster’s panel.

    Permanent Redirect 301 via .htaccess

    This method of installing redirects is the most popular and simplest. Although, I must admit, everything is not as simple as it seems, so I plan to write a separate post about htaccess. On the plus side this method It can be noted that the redirect is triggered at the server level and before the processing of any site scripts starts and does not carry any additional load.

    You probably already have a .htaccess file on your server (at the root, where the main index.php is). If this file is not visible:

    • Check the settings of the ftp manager, it can hide systems and files, which is the htaccess file
    • Go to the file manager through the hoster's control panel and check the permissions for the file. I don’t mean CHMOD, but a group and a user, for example, there may be root user, and you connect via ftp using the domain owner's user access.
    • The file may simply not exist :) Then it should be created, but under Windows sometimes a problem arises, because in fact, the .htaccess file is seen by the system as a file without a name and only with an extension. I suggest a simple way - create a regular txt file, add the line “RewriteEngine On” (without quotes) to it, upload the txt file to the server, rename the file to .htaccess on the server

    Most of the edits related to the redirect should be written at the very beginning of the file after the line “RewriteEngine On” so that these rules are processed first. It is important to follow the sequence of actions, because commands are processed by the server line by line from the very beginning until the first occurrence. In other words, you should always start with a particular sample and end with a more general sample.

    Let's look at some of the most common and useful examples:

    301 redirect for a domain from www.site.ru to site.ru

    RewriteCond %(HTTP_HOST) !^www\.(.*) RewriteRule ^(.*)$ http://www.%1/$1

    The above redirect options work great and do not require any changes on your part - just paste into. htaccess file. However, to be 100% safe, I would advise you another option:

    RewriteCond %(HTTP_HOST) !^www.site.ru$ RewriteRule ^(.*)$ http://www.site.ru/$1

    RewriteCond %(HTTP_HOST) !^www.site.ru$ RewriteRule ^(.*)$ http://www.site.ru/$1

    RewriteCond %(HTTP_HOST) !^site.ru$ RewriteRule ^(.*)$ http://site.ru/$1

    RewriteCond %(HTTP_HOST) !^site.ru$ RewriteRule ^(.*)$ http://site.ru/$1

    The first is for those who have a main domain with www, the second is for those without www. Accordingly, in both examples you need to enter the name of your domain instead of “site”.
    So, why are these options better? Very simply, they check not only the absence/presence of www in the domain name, but also check the domain name for full compliance.
    Live example: Surely you have encountered the fact that unexpectedly a site can be indexed by a service address on the hosting (such an address is issued so that the site can be accessed before linking your real domain), some mirror, or even an IP address! So, the universal rules will only verify the absence/presence of www, and it does not matter which domain the user or search robot accesses.
    So, by using the advanced option, you will be 146% sure that your site will be accessible only and exclusively using the domain name you personally specified and taking into account www. I only use this option and recommend it to you!

    301 redirect from http to https

    In light of the massive transition of sites to a secure protocol, you need to know how to redirect from http to https. By the way, if you haven't chosen an SSL certificate yet, you should read my post about .

    Below I offer you several options for a 301 redirect from the http to https protocol, which may or may not work depending on the configuration of your server, but one of the rules will definitely suit you:

    RewriteCond %(HTTPS) !=on RewriteRule ^(.*)$ https://%(HTTP_HOST)/$1

    RewriteCond %(HTTPS) !=on RewriteRule ^(.*)$ https://%(HTTP_HOST)/$1

    RewriteCond %(SERVER_PORT) !^443 $ RewriteRule ^(.*)$ https://%(SERVER_NAME)%(REQUEST_URI)

    RewriteCond %(SERVER_PORT) !^443$ RewriteRule ^(.*)$ https://%(SERVER_NAME)%(REQUEST_URI)

    RewriteCond %(ENV:HTTPS) !on RewriteRule ^(.*)$ https://%(HTTP_HOST)%(REQUEST_URI)

    RewriteCond %(ENV:HTTPS) !on RewriteRule ^(.*)$ https://%(HTTP_HOST)%(REQUEST_URI)

    RewriteCond %(HTTP:X-HTTPS) !1 RewriteRule ^(.*)$ https://%(HTTP_HOST)/$1

    RewriteCond %(HTTP:X-HTTPS) !1 RewriteRule ^(.*)$ https://%(HTTP_HOST)/$1

    RewriteCond %(HTTPS) off RewriteCond %(HTTP:X-Forwarded-Proto) !https RewriteRule ^(.*)$ https://%(HTTP_HOST)%(REQUEST_URI)

    Redirect from https protocol on http (honestly, I don't know why you might need this):

    RewriteCond %(HTTPS) =on RewriteRule ^(.*)$ http://%(HTTP_HOST)/$1

    RewriteCond %(HTTPS) =on RewriteRule ^(.*)$ http://%(HTTP_HOST)/$1

    Recently I wrote very detailed instructions. If you are planning a move from https to https, you owe it to yourself to read it!

    Let me bring some clarity to the incomprehensible gobbledygook:

    • RewriteCond denotes a condition that, if matched, will execute the RewriteRule. Regular expressions are used to define string patterns.
    • Server Variables:
      • %(REQUEST_URI) - part of the URL without a domain name and GET parameters, for example, for the page you are currently reading: blog/post/4393,
      • %(HTTP_HOST) - host or domain name, for example: website
      • %(QUERY_STRING) - a string with a set of GET parameters, that is, the part of the URL after the question mark (and before the anchor grid, if there is one).
      • %(REQUEST_FILENAME) - full path to file system server to a file or script corresponding to this request..php, but in the server file system this is the terrible line /var/www/site/data/www/site/index.php.
        It happens that when making a redirect, you get an unexpected result, for example, you wanted to remove the parameters post=17434801_4060 in the address http://site.ru/page-name?post=17434801_4060 , indicated the corresponding rules (they will be written about below), but in the end we got the line http://site.ru/usr/local/www/site.ru/www/page-name - we got rid of the parameters, but got a strange address. This is all because you did not specify a RewriteBase / directive at the beginning of the file after RewriteEngine On, which sets a specific, base URL for transformations in the context of a directory.
    • Metacharacters are used to define groups of characters or "tags" in a pattern:
      • ^ — line start mark,
      • $ is the end of line mark,
      • ! – denial,
      • \ - escape slash, allows you to consider the metacharacter following it as a regular character,
      • . – dot, denotes any character, but only one,
      • () – grouping.
    • Modifiers are placed after regular characters, metacharacters or their groups and expand the possibilities of using templates:
      • ? — the symbol is repeated 0 or 1 time,
      • * — Repeated from 0 to 65536 times,
      • + — Repeats from 1 to 65536 times.
    • Flags define additional options for of this rule and are listed in square brackets separated by commas:
      • NC - (nocase) disables case checking.
      • R - (redirect) stops the conversion process and returns the result to the client browser as a redirect to this page(302, MOVED TEMPORARY). With this flag you can specify a different result code, for example R=301 will return a redirect with code 301 (MOVED PERMANENTLY). As you understand, this is exactly what we need.
      • L - (last) stops the conversion process and the current link is considered final.

    The most popular case is a 301 redirect from index.php (html) to the main page. On 90% of sites, there is a problem of duplicating the main page at the addresses http://site.ru and http://site.ru/index.php (or index.html, index.htm or any other option, it doesn’t matter, or even all at once). Somewhere this is obvious, when, for example, a link from the logo leads to site.ru, and a link in the menu leads to site.ru/index.php, somewhere it is not obvious, when a duplicate is found when entering the address from index.php manually . It is important to simply solve the problem. And I offer a universal option, here it is:

    RewriteCond %(THE_REQUEST) ^(3 ,9 )\ /index\.(php|html|htm)\ HTTP/ RewriteRule ^(.*)index\.(php|html|htm)$ $1

    RewriteCond %(THE_REQUEST) ^(3,9)\ /index\.(php|html|htm)\ HTTP/ RewriteRule ^(.*)index\.(php|html|htm)$ $1

    Just paste this code unchanged after the line after the "RewriteEngine On" line and no problem!

    Many who begin to struggle with duplicates on the site wonder where such links come from., which duplicate the main page http://site.ru/page-name.html &post=-1234567_8901? Where did the prefix &post=-1234567_8901 come from - this “good” is taken from VKontakte, when someone shares a link to your site on their wall, in a group or public, a similar line is automatically added, apparently to track some statistics.

    To get rid of this nonsense once and for all you need to add to htaccess:

    RewriteCond %(REQUEST_URI) ^(.*)\&sa= RewriteRule ^(.*)\&sa=(.*)$ $1

    As you can see, there is no difference between this and the previous case, even if you have &post= or &sa= or whatever in the url, the solution is the same, you just need to replace the obvious parts of the code. It’s clear, right?

    Getting rid of parameters or tags in the address

    The question was asked in the comments and many times on the forum, so it cannot be ignored. What to do with such duplicates: http://site.ru/?abrakadabra or a more real case http://site.ru?utm_source=twitterfeed&utm_medium=twitter

    This case is slightly different from the next point, where we will get rid of parameters for the PHP script, since here we do not pass the usual address and parameters to the script. Here's the solution:

    RewriteCond %(QUERY_STRING) ^lang=ru$ RewriteRule ^(.*)\.php\?(.*)$ $1\.php

    %(QUERY_STRING) is a string with a set of variables for PHP, the part of the URL after the question mark (and before the anchor hash, if there is one).

    Call url - http://site.ru/index.php?lang=ru

    RewriteCond %(QUERY_STRING) ^lang=ru $
    The requested url falls under this rule, there are no other rules, so the RewriteRule will be executed in the line below.
    RewriteRule ^(.*) \.php\?(.*) $ $1 \.php

    Source url: http://site.ru/index .php?lang=ru
    Url parsing template: ^(.*) \.php\?(.*) $
    The URL will be parsed into variables: $1 = http://site.ru/index, $2 = lang=ru and assembled back in the form http://site.ru/index .php ($1 \.php)
    And then there will be a 301 redirect to the new url.

    Example of rules when changing the site structure

    RewriteRule ^post/category/(.*)$ blog/category/$1 RewriteRule ^post/(.*)$ blog/post/$1

    RewriteRule ^post/category/(.*)$ blog/category/$1 RewriteRule ^post/(.*)$ blog/post/$1

    These are the lines I had to add to the htaccess file when I changed the structure of my blog.

    Previously, I had the following addresses: http://site/post/4358 and http://site/post/category/seo, which somehow broke the logic in the structure - after all, the blog is only part of the site, but for some reason the posts belong to the site, not the blog, and the categories belong to the posts, which is also completely illogical..info/blog/category/seo - now the blog is a separate section of the site, and the posts belong to it, and the categories belong to the blog, not the posts.

    From the same example it is clear that it is important to follow the sequence of rules. If I swapped the lines, that is, the line RewriteRule ^post/(..info/blog/post/category/seo would come in front and not as it should on http://site/blog/category/seo.

    And the last example is parsing common mistake with the address from the server root

    For example, you decided to fix a problem when the category page is available at two addresses http://site.ru/razdel/podrazdel/index.php and http://site.ru/razdel/podrazdel/. The second url is correct and the main one, and the url with index.php at the end is a complete duplicate that needs to be disposed of.

    In order to redirect from index.php to a category, you write the following rule:

    RewriteEngine On RewriteBase /

    301 redirect from page to page to a new address

    The simplest case is when you need to redirect one page to another address. If you need to make a redirect for several pages, you will have to write several rules, but in this case it is better to use the templates described above. There are several completely identical syntax options:

    Redirect 301 /page-name1.html http://site.ru/page-name2.html Redirect permanent /page-name1.html http://site.ru/page-name2.html RedirectPermanent /page-name1.html http http://site.ru/page-name2.html

    Redirect 301 /page-name1.html http://site.ru/page-name2.html Redirect permanent /page-name1.html http://site.ru/page-name2.html RedirectPermanent /page-name1.html http http://site.ru/page-name2.html

    Choose one of the three, but personally I prefer the first option - it’s shorter, simpler and more understandable. By the way, here site.ru may not necessarily be the same domain, but any other.

    Let's finish with .htaccess and move on to PHP.

    Permanent Redirect 301 using PHP

    I usually use PHP redirect when there are difficulties with .htaccess or it turns out that the PHP function turns out to be more logical and understandable.

    The syntax of a 301 redirect in php looks like this:

    header(); header("Location: http://site.ru"); die("Redirect" );

    header("HTTP/1.1 301 Moved Permanently"); header("Location: http://site.ru"); die("Redirect");

    These lines tell the client’s browser that it is necessary to permanently redirect from some requested page to the address http://site.ru. In this case, http://site.ru can be not only the address of the main page of the current site, but can also be any other site. If something went wrong and an error occurred, then in the browser window we will see the inscription “Redirect”.

    To make it clearer, here are a few examples of functions that I wrote for my blog site, trying to solve certain problems.

    A function that allows you to remove a certain part from the url

    if (strpos($_SERVER["REQUEST_URI" ], "http://site" ) !== false) ( $real_page_url = "http://site" .str_replace ("/http://site" , "" , $_SERVER["REQUEST_URI" ]); header ( "HTTP/1.1 301 Moved Permanently"); header ( "Location: $real_page_url" ); die("Redirect" ); )

    if (strpos($_SERVER["REQUEST_URI"], "http://site") !== false) ( $real_page_url = "http://site"..1 301 Moved Permanently"); header("Location: $real_page_url"); die("Redirect"); )

    Once I had a problem that a bunch of 404 errors appeared in the webmaster panel, the addresses of these pages were like http://alaev..e. From somewhere in the address a duplicate site address appeared. And then I wrote a function that checks whether the URI (note, not the URL, but the URI) contains the entry “http://site”, and if it does, we cut out this piece from the address and write the result to the $real_page_url variable, and then we do a 301 redirect to the correct address from the variable.

    Function that removes trailing slash from URL

    if (($_SERVER["REQUEST_URI" ], - 1 , 1 ) == "/" ) ( $requested_url = rtrim($requested_url, "/" ); header ( "HTTP/1.0 301 Moved Permanently"); header("Location: $requested_url"); die("Redirect" ); )

    if (($_SERVER["REQUEST_URI"], - 1, 1) == "/") ( $requested_url = rtrim($requested_url, "/"); header("HTTP/1.0 301 Moved Permanently"); header( "Location: $requested_url"); die("Redirect");

    Like this simplest function, which looks to see if the requested address of the page has a slash at the end, and if there is one, the slash is cut off and a 301 redirect occurs to the address without the slash.

    There are many more options that allow you to issue a redirection command to different languages programming, such as ASP, Ruby on Rail, etc., but I’m not familiar with these languages, so I won’t be clever here and fool you. Redirects are also possible using the meta refresh meta tag, as well as redirects to javascript– but this is the fate of dishonest doorway developers, and search engines do not understand these redirects; they receive a response from the server 200 OK. So we are not considering these options.

    Permanent Redirect 301 for nginx server

    Remember I wrote about a mirror of my site, accessible via IP? As a result, the problem was solved by a redirect written in the server configuration file, usually located here /etc/nginx/nginx.conf. The following lines were written there:

    server ( listen 1.2.34.123:80 default; server_name _; rewrite ^/(.*)$ http://site.ru/$1 permanent; )

    server ( listen 1.2.34.123:80 default; server_name _; rewrite ^/(.*)$ http://site.ru/$1 permanent; )

    It says here that if an IP address is accessed through port 80, then you need to do a permanent redirect to site.ru.

    However, technical support did not recommend that I do this with the words: “It would be more correct to configure the HTTP server in such a way that it simply closes the connection if it is accessed at an address that is not explicitly specified in the HTTP server configuration, this is the most reliable, simple , a safe and least demanding option for server resources. After some time, pages that are no longer accessible will likely be kicked out of the search engine index.”

    The next advice was this: “When you need to simply close the connection instead of redirecting, then instead of the line, specify “rewrite ^/(.*)$ http://site.ru/$1 permanent;” such a line "return 444;". Then run: "invoke-rc.d nginx reload"".

    Maybe this will help someone.

    Examples of redirects in the most common cases

    Redirect for the domain www.site.ru to site.ru

    server ( listen 80; server_name site.ru; rewrite ^ http://www.site.ru$request_uri? permanent; )

    Redirect from the address http://site.ru/index.php to http://site.ru/

    location = /index.php ( if ($request_uri = /index.php) ( rewrite ^ http://$host? permanent;#301 redirect ) fastcgi_pass unix:/tmp/fastcgi.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params)

    location = /index.php ( if ($request_uri = /index.php) ( rewrite ^ http://$host? permanent;#301 redirect ) fastcgi_pass unix:/tmp/fastcgi.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params)

    Something like this. I’m not good at setting up configs for nginx; I always make do with Apache settings, so if you have any questions about nginx, I’m unlikely to be able to help you...

    How to check HTTP headers and server response statuses

    In this section I wanted to describe various services and plugins for checking the server response, but I understand that this post is already so large in volume that I will have to limit myself to just links to extensions for Chrome and Firefox browsers.

    HttpFox add-on for Firefox

    HttpFox (here is a link to the addon) is my favorite http header tracking tool. HttpFox shows the progress of page loading line by line, which allows you to track, for example, chains of redirects and, in general, the order and speed of page loading. If you use Mozilla, I definitely recommend it.

    HTTP Headers Extension for Chrome

    I myself do not use the HTTP Headers extension (here is a link to it), but the Internet advised me to pay attention to it. If you have better options, please post in the comments.

    This concludes my terribly long and boring post, friends.
    Thank you for reading to the end, I hope you found it really useful.


    If you want to correctly configure 301 redirects on your website, then SeoProfy have prepared a step-by-step guide that explains and shows all the details and nuances.

    The 301 redirect guide consists of two parts:
    - An article with code examples and the guide itself (if you immediately need a code example, it’s better to immediately scroll through the infographic)
    - Visual, detailed infographics

    301 redirect is important for search engine promotion and in this guide you will find answers to the most basic questions on how to correctly use a redirect for different situations.

    What is a redirect?

    A redirect is a way to redirect users and search engines to a different URL than the one they originally requested. Below are descriptions of some of the most commonly used types of redirects.

    301 Moved Permanently

    A 301 redirect is a permanent redirect that conveys about 90-99% of the link juice. This redirect indicates that the page has been moved to a new address and the old url should be considered outdated.

    302 Found (HTTP 1.1) / Moved Temporarily (HTTP 1.0)

    302 redirect is a temporary redirect. This redirect transmits 0% of the link juice and, in most cases, should not be used. On at the moment The Internet runs on the HTTP protocol, which determines how to process URLs. In the two versions of this protocol, this server response has a different response status:

    HTTP 1.0: 302 server response is “Moved Temporarily” - the current document has been temporarily moved to another URL.

    HTTP 1.1: the server response changed to “Found” - the current document was found.

    307 Moved Temporarily (HTTP 1.1 Only)

    The 307 redirect in the HTTP 1.1 protocol became the receiver of the 302 redirect. While mainstream search bots will begin to treat it as analogous to 302, for almost all cases it is best to use 301. The exception to this rule is when the content has only actually moved temporarily (for example, during maintenance) and search engines already understand that your server is compatible with HTTP 1.1. But, since it is almost impossible to determine whether search engines have actually realized that your server is compatible with this new protocol, it is better to use a 302 redirect for content that has been temporarily moved.

    Other types of redirects

    There are also other types of redirects: Meta Refresh or using javascript - which are performed at the page level, and not at the server level. Here's what a typical Meta Refresh redirect looks like:

    But it is advisable to use these redirects extremely rarely, since spammers and doorway men love to abuse them. In addition, when using these redirects, almost no link juice is transferred.

    Examples of use

    Canonicalization of a website domain or how to merge a domain?

    To merge a domain from www to non-www:
    RewriteCond %(HTTP_HOST) ^www.site\.com$
    RewriteRule ^(.*)$ http://site.com/$1

    To merge from without www to with www:
    RewriteCond %(HTTP_HOST) ^site\.com$

    In order to correctly choose which option to glue, it is advisable to look at:

    Which of these options is more in the top?
    - for which of the options more pages in the index

    Canonicalization of a slash at the end of a URL

    When designing a website, it is important to decide on one format, using a slash at the end of the URL, since for search engines there are 2 URLs of the form:

    http://www.site.com/cat1/

    http://www.site.com/cat1

    are different. Therefore, after you have decided exactly how you will have it on the site, then you need to enter the following redirects

    To remove the trailing slash:
    RewriteCond %(HTTP_HOST) (.*)
    RewriteCond %(REQUEST_URI) /$
    RewriteRule ^(.*)(/)$ $1

    To add a slash at the end address bar:
    RewriteCond %(REQUEST_FILENAME) !-f
    RewriteCond %(REQUEST_URI) !(.*)/$
    RewriteRule ^(.*[^/])$ $1/

    Redirecting one page to another page:
    Redirect 301 /oldpage.html http://www.site.com/newpage.html

    Redirect for home page duplicates

    This code ensures that any home page address that includes multiple versions of the page name deeplinks, such as default.htm or index.html, will redirect to the canonical home page, http://www.site.com:
    RewriteCond %(THE_REQUEST) ^(3,9)\ /([^/]+/)*(default|index|main)\.(html|php|htm)\ HTTP/
    RewriteRule ^(([^/]+/)*)(default|main|index)\.(html|php|htm)$ http://www.site.com/$1

    Directory redirect

    If your directory structure is displayed in the url, then if you do re-cataloging, the url will change accordingly. In this case, you need to enter the following redirect:
    RewriteRule ^(.*)/old-catalog/(.*)$ $1/new-catalog/$2

    But, if the URL of the old catalog begins immediately after the domain: www.site.com/old-catalog/, then you need to use the following code
    RewriteRule old-catalog /(.*) / old-catalog /$1

    Redirect when changing file extension

    If you suddenly moved to another platform or CMS and only the extension of the URLs changed, then in this case the following redirect will help you:
    RedirectMatch 301 (.*)\.php$ http://www.site.com$1.html

    Examples of use to protect a website from multiple duplicate pages

    Redirect from different domains and subdomains

    If you purchased several domains from different domain zones or you developed a new website and put it on a subdomain, but forgot to close this subdomain from indexing, then you need to redirect to the main domain:
    RewriteRule ^(.*)$ http://www.site.com/$1

    Thus, all domains such as www.site.ru, www.site.net, test.site.com will be redirected to the site www.site.com.

    How to remove multiple slashes/dashes in a URL

    Sometimes “by chance” several slashes may appear in the URL, for example, www.site.com/catalog////page-1.html. In such cases, you need to do a 301 redirect to a page with one slasher www.site.com/catalog/page-1.html:
    RewriteCond %(REQUEST_URI) ^(.*)//(.*)$
    RewriteRule. %1/%2

    Similarly, you can merge several hyphens into one in a URL: from www.site.com/catalog/page-1.html to www.site.com/catalog/page-1.html:
    RewriteCond %(REQUEST_URI) ^(.*)--(.*)$
    RewriteRule. %1-%2

    How to redirect from any URL to a URL only in lowercase

    Since search engines take into account the case of letters, when designing a site it is desirable that all URLs be in lower case. However, if you initially missed this point, then it is best to use the following code for a redirect at the php script level:
    $lowerURI=strtolower($_SERVER["REQUEST_URI"]);
    if($_SERVER["REQUEST_URI"]!=$lowerURI)
    {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: http://" . $_SERVER["HTTP_HOST"] . $lowerURI);
    exit();
    }

    How to move to a new domain? Optimal 301 redirect strategy

    The optimal strategy for moving to a new domain, taking into account the wishes of the two main Runet search engines Yandex and Google, is:

    Page-by-page 301 redirect from the old site to the new one.
    - at the same time, we do not do a redirect for the robots.txt file, but write in it the Host directive to the new domain.

    Then the code for setting up a redirect on the old site may look like this:
    RewriteCond %(REQUEST_FILENAME) robots.txt$
    RewriteRule ^([^/]+) $1 [L]
    RewriteCond %(HTTP_HOST) !^www\.site\.com
    RewriteRule ^(.*)$ http://www.site.com/$1
    and the robots.txt file for the old site:
    User-agent: Yandex
    Disallow:
    Host:newsite.com

    Generating 301 redirects

    If you are not very technically savvy, then you can use services for generating basic redirects:

    On such services, you can only enter your own data and immediately receive ready-made code for redirects between domains, directories or URLs.

    How to check 301 redirect

    After each change in the logic of the 301 redirect, you need to check the functionality of the site:

    Is the site working at all: go to the main page)

    Walk through the main sections and pages of the site

    You can also use the following services to more thoroughly check the processing of redirects:

    How and when is it better to use 301 redirects vs Canonical

    Although there are some nuances, Google provides some clear rules so that it understands exactly what we want to say. In a very simple situation, this is how search engines understand these instructions:

    301 - Hey, Search Engines: my page is no longer here and it has permanently moved to new page. Please remove the old page from the index and transfer its weight to the new page.

    Canonical- Hey Search Engines (as for most search engines): I have several versions of this page (or content), please only index the version of the page that has canonical. I will keep other pages available for people to see, but Search Engine, don't include them in your index and please pass the weight to my preferred page.

    When is it better to use a 301 redirect?

    Default is the preferred method

    For pages: if the page has moved permanently or has been replaced with a new address

    For domains: if the site has moved to a new domain (site sale, rebranding, etc.)

    For 404 pages and content that has lost its relevance (subject to appropriate content). For example, if a product is removed from a certain catalog, you can redirect to a similar product, or to the url category to which this product belonged.

    When is it better to use rel="canonical"?

    When 301 redirects cannot be implemented or will take too long to implement

    Pages with several different urls are essentially one page (for example, sorting a directory, tracking affiliate links, ...)

    Cross-domains, when both sites are similar, but similar content needs to be left on each of the domains.

    Total

    Errors when using redirects

    Any multi-step redirect. If possible, it is advisable to avoid multi-step redirects so that it works faster and the maximum link juice is transferred.

    Use not the right type redirects. When choosing a redirect type, you need to take into account the nuances of each of them.

    Implementation of internal redirects without changing links to new addresses. After implementing all the redirects on your site, you need to check that each page of your site already links to a new one and that within the site you do not have links to the pages from which the redirect occurs.

    Redirect to irrelevant pages/content. It is always advisable to place a redirect on the most relevant page: either on a similar page, or on a branch of the directory/section to which this page belonged.

    Not right choice using rel=canonical vs 301 redirect. See above.

    A redirect whose end point is not the 200th page. The redirect should lead to a properly working page with a 200 server response. Otherwise, it is advisable not to confuse search robots and give a 404 response.

    Robots.txt redirect. Because, for example, you need to specify the Host directive for Yandex when merging domains.

    Let's look at the infographics:

    Download the infographic.