Thought redirect php. How to make a redirect. All types. Outputting JavaScript redirect code using the PHP echo() function

Home > Programs > Apache

301 redirect - correct redirection via htaccess and php header

The 301 redirect (301 Permanent Redirect) is used in several cases: when changing a domain, when moving a site page, to merge the site name with and without www. This is important for conveying Page Rank (PR) and retaining search traffic.

I myself was faced with the need for it when, after moving my portal from the com zone to ru, I discovered that Google, Yandex and other search engines naturally do not “forget” the old site (partly also due to the fact that I had an incorrect its own page was installed to handle 404 errors, which returned the response code 200 OK). Moreover, Google left PR=0 for the new site for six months, although it remained PR=4 for the old one.

The topic of 301 redirects is constantly discussed in various SEO forums, and each search engine has special sections in its help system. While I was figuring it out, I found the options for organizing a redirect listed below, some of which I tried myself.

301 redirect is best method maintaining your positions in search engines when you move a page or site. Code "301" is interpreted as "moved permanently".

  • Simple redirect (in .htaccess file or httpd.conf for Apache): Redirect 301 / http://www.you.com/new.htm
    Where:
    Redirect 301 is an instruction saying that the page has been moved
    / - means that everything from the top level of the site, including all subdirectories, will be redirected
    http://www.you.com/new.htm - new page or site (don’t forget to put the last “/” if the redirection is to the site).

    To redirect only a page, keeping the old page's PR:
    Redirect 301 /old/old.htm http://www.you.com/new.htm
    Where:
    /old/old.htm - path and name of the old page

    Similar syntax for site redirect:
    Redirect Permanent / http://www.you.com/

    Directory redirect example:
    Redirect Permanent /old-directory http://www.domain.com/new-directory/

    For example, we will redirect those who entered test to www.test.com, the rest to enter.test.com (the order of the entries is important):

    Redirect permanent /test http://www.test.com/ Redirect permanent / http://enter.test.com/

    Note: For my purposes (changing the domain), the first option of a simple 301 redirect was enough.

  • Using mod_rewrite (written in the .htaccess file):

    The classic problem of merging site names with and without www is solved like this:

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

    or alternative syntax:

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

    The notation means: redirect the client and send it a status code of 301 (R=301) and make this rule last (L).

    Redirecting an old domain to a new one:

    Options +FollowSymLinks RewriteEngine on RewriteRule (.*) http://www.newdomain.com/$1

    For example, if you want the rewrite.html file to be loaded instead of rewrite.htm, add to .htaccess:

    RewriteEngine on RewriteBase / RewriteRule ^rewrite\.htm$ rewrite.html

    To replace all .htm files with .html files:

    RewriteEngine on RewriteBase / RewriteRule ^(.*)\.htm$ $1.html
  • Redirect to PHP: It is better to specify HTTP/1.1, since older ones do not support shared hosting. Remember that before header is called, nothing should be printed (e.g. echo or print). Therefore, it is better to put this code at the beginning of the PHP script. A more complete version of a php redirect with saving the transmitted page and call parameters:
  • Redirect to ASP
  • Redirect to ASP.NET private void Page_Load(object sender, System.EventArgs e) ( Response.Status = "301 Moved Permanently"; Response.AddHeader("Location","http://www.new-url.com") ; )
  • Redirect to ColdFusion
  • Redirect using meta refresh

    where 0 is the redirection delay in seconds, newdomain.com is the page to which we will redirect. Some older browsers do not support meta refresh with a value of 0; for compatibility, you can set it to a non-zero value, although, in my opinion, this is no longer relevant. Such a redirect will not be able to glue your sites together (with or without www) and transfer PR, since it is ignored by search engines. It returns a 200 OK code, which is a normal page. This technique is popular with spammers, so it should only be used for pages that will not be indexed.

  • Redirect using JavaScript

    JavaScript redirect options are often implemented using the setTimeout("function", delay) function.

    For example, to automatically click on the "Submit" button of the "searchform" form 0.1 seconds after loading the code:

    setTimeout("document.forms["searchform"].Submit.click()", 100);

    You can assign any action to the "Submit" button, for example, open a new URL in this window. By the way, such redirects are more common when organizing Dorways - the User’s browser will be redirected to another page, and a search robot that “does not understand” JavaScript will index this page, which is inaccessible to the user. Doorway developers post text on it, stuffed with “necessary” keywords.

    To simply redirect to another page, you can insert after one of the JavaScript code options:

    • location="http://www.newdomain.com";
    • document.location.href="http://www.newdomain.com";
    • window.location.reload("http://www.newdomain.com");
    • document.location.replace("http://www.newdomain.com");
    In the latter case, it will no longer be possible to return to the page that performed the redirection, since its address is erased from history, which is often necessary. If you need a time delay, you can register location="http://www.newdomain.com"; as a function and insert it into setTimeout("function()", delay_in_ms); A redirect to JavaScrupt is not a 301 redirect and will not transfer the PR of the page and will not be able to ensure its merging.
  • Let us additionally note some features of redirects:
    • Redirect methods with .htaccess only work on Linux servers having Apache with the Mod-Rewrite module enabled.
    • Using .htaccess creates additional load on the Apache server; it is more efficient to write the same commands in its hpptd.conf configuration file, but, as a rule, the webmaster does not have access to it.
    • 301 redirect allows you to save traffic and transfer PR pages to search engines (for Google for sure).
    • The process of gluing and transferring PR takes a long time - up to several months and also depends on the search engine, so do not delete the old page or site until the final transfer occurs.
    • some search engines require sites to be linked together additional settings, for example, for Yandex you need to additionally specify robots.txt

    Conclusion. A safe way to redirect old pages to new ones or an old site to a new address, while maintaining positions in search engines, is to use a 301 redirect, which will also allow you to transfer the old Page Rank of the page to the new site.

    45.4K

    Anyone can send. But redirecting correctly is a whole art. But redirecting users to the right path on the Internet is even more difficult. A redirect to php is best suited for this.

    What kind of redirect?

    In web programming, situations arise when you need to redirect a user following a link to another address. Of course, at first glance, implementing such a redirect looks a little “illegal.” In practice, such a redirect is in demand not only among attackers, but also among honest webmasters:


    In what cases may a redirect be required:
    • When the site engine is replaced, the architecture of the entire resource changes as a result. Then the problem arises of how to make a redirect;
    • When the structure of a resource is redrawn, entire sections or one material are added, deleted or transferred. While this process is happening, it is temporarily possible to redirect the user to the desired section;
    • If the site has recently changed its domain name, after changing the domain name, the old one will still appear in search results for some time. In this case, the user will be redirected to the new domain search engine automatically;
    • During the authorization process, as a rule, on a large website there are two groups of users: ordinary visitors and resource administrators. In this case, it makes sense to implement a redirect for each user according to his rights and role. After authorization, the site administrator or moderators go to the administrative part of the resource, and visitors go to the user part of the resource.
    Features of redirect to php

    Unlike other languages, PHP has some advantages in implementing redirects:

    • Php is a server-side programming language. Therefore, the redirection will not occur in the html code of the pages displayed in the browser, but in a script hosted on the server;
    • Redirecting to php can be implemented in several ways. Which greatly expands its application;
    • Thanks to data processing on the server, redirection implemented with using php, less susceptible to the effects of search engine filters.

    To redirect in PHP, the header() function is used. It is used to send the http header. Its syntax is:

    void header (string $string [, bool $replace = true [, int $http_response_code ]])

    Arguments accepted by the function:


    • string $string – header string;

    There are two types of this argument. The first one is for sending the connection status code. It starts with "HTTP/". The other type sends a status code (REDIRECT 302) to the client browser along with the header. This argument begins with "Location:"

    • bool $replace is an optional attribute of type bool . Responsible for overriding the previous header. If set to true , the previous header or headers of the same type will be replaced. If the argument is set to false , then the header will not be rewritten. By default, this value is set to true ;
    • http_response_code – the argument forces the HTTP response code. Installation of the code will be successful provided that the string argument is not empty.

    The HTTP status code is part top line server response. The code consists of three numbers, followed by an explanatory inscription on English language. The first digit is responsible for the status class. The redirect corresponds to codes from 300 to 307. Full description can be found in the relevant technical documentation.

    When using the header() function for a redirect external links The location of its call is of great importance. In the code it should be located above all html tags:

    Using the header() redirect

    To demonstrate the function on local server you need to create two files. Let's call one of them redirect.php , and the other redirect2.php . Inside the first one we will place a function call in the following format:

    In another file we put the line:

    echo "Hello! You are in the redirect2.php file";

    Some more practical examples of using a redirect to php:

    • Force http status code – when using the first argument of the header() function of type “location”, the default status code “302” (temporarily moved) is passed to the header. This can become a problem when moving a resource to another domain name. In search engines, such temporary redirection may take longer. After all, the search engine constantly analyzes the status code. And it says “temporarily moved”. Example of forced rewriting of status code "302" to "301" (permanently moved):

    Rewriting is also possible in two stages. The first line rewrites the status code, and the second redirects to a new address.

    I recently showed how you can make a redirect to htaccess, now I offer the option of php redirect () - as an alternative to the 301 server redirect. Why is this necessary? - but because it is not always possible to do the correct redirection on htaccess everywhere.

    And so, first you need to write a condition under which the redirection will work. In WordPress, we write the code in the header.php file or in any other file of your theme above the get_header() function at the very beginning, before the HTML tags. The code will be like this:

    If you need php redirection to wordpress in a local location, for example we want to redirect from one category to home page, you can write the above code in any theme file that triggers the output of a category (for example category.php) above the header call code get_header();

    How does php redirection in the response line work?

    With PHP redirection, we receive exactly the same response from the server, as if we did it through the server config, adjusted for this, the processing speed will be slightly lower. Screenshot of the server response in Chrome:

    The same 301 redirect is only implemented in PHP.

    Why use 301 php redirect There is a situation when you need to fix an entire category, taxonomy, VP label or block a Custum Post Type without deleting them. For example, we have transferred the content, but the links are already indexed. In this case, a 301 php redirect will help us, which we can insert anywhere. Of course, such a redirect is inferior in performance to a redirect from the server settings, but writing a huge mask for a taxonomy or CPT is a very big hassle. What if 301 php redirect doesn't work?

    A redirect to PHP may not work due to the condition not being triggered, so first you need to:

  • Check the condition in PHP, for example throw there echo "Test";
  • If the condition is triggered, then we need to look at where our redirection code is located; if it is below the HTML tags, then this is our problem. We must rise above everything
  • Thanks to the ability to redirect a site from PHP, we can implement a redirect mechanism where htaccess cannot cope, or rather we cannot cope :)

    If you have any questions, write them in the comments or to me at .

    Last modified on February 25th, 2017 by Vincy.

    PHP redirect mechanism is used to navigate the user from one page to another without clicking any hyperlinks. This will be helpful in such circumstances where the redirect should be done in the background. For example, when the user is accessing payment gateway, the redirect should automatically be taken place to notify URL using PHP script.

    PHP provides predefined function, named header(),for URL redirection. Using this header() function, we need to send location header by specifying URL to which the page should be redirected.

    Unlike where there are several ways to handle URL redirect works based on the browser, PHP avoids such confusion and have header() function create the same effect in all browsers. For that only, we have concluded with JavaScript redirect article that server side redirect is preferable.

    PHP Redirect Syntax header("Location: target-url");

    In the above syntax of PHP redirect, we need to replace with a valid URL to which we want to move. We can specify either absolute URL or relative URL for this location header. If we specify relative URL, it will search for the page in our domain where we exist.

    Note: Before specifying page URL for location header, we should make sure that the page exists.

    Caution before Redirect

    Before executing PHP redirect, we should ensure about, no output is sent to the browser before the line where we call the header() function. For example,

    Echo "PHP Redirect"; header("Location: site");

    This script will display the following warning notice to the browser.

    Warning: Cannot modify header information - headers already sent by (...

    It is not only applicable for header function, rather for all the PHP functions like set_cookie(), session_start() and etc., whatever can modify the header. For that, we should remove all content which will stop sending location header to the browser.

    Possible Ways of Sending Output
    • HTML content like text or tags.
    • Unnecessary white spaces before PHP delimiters.
    • PHP error or warning notices that occur before calling redirect.
    • PHP , like, echo(), print().
    Safety Measures from output being Sent before PHP Redirect
    • Since HTML content should be sent before the redirect, we can separate PHP logic from HTML content.
    • For being in the safety side we can put exit command after redirect statement of PHP file. For example, header("Location: site"); exit;
    • We can enable PHP output buffering to stop sending output to the browser and stored into a buffer instead.

    (PHP 4, PHP 5, PHP 7)

    header — Send a raw HTTP header

    Description

    header (string $header [, bool $replace = TRUE [, int $http_response_code ]]) : void

    header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more information on HTTP headers.

    Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include , or require , functions, or another file access function, and have spaces or empty lines that are output before header() is called.


    The same problem exists when using a single PHP/HTML file.

    Parameters

    The header string. There are two special-case header calls. The first is a header that starts with the string "" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

    The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT(302) status code to the browser unless the 201 or a 3xx status code has already been set.

    Replace

    The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example:

    Http_response_code

    Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the header is not empty.

    Return Values

    No value is returned.

    Changelog Version Description
    5.1.2 This function now prevents more than one header to be sent at once as a protection against header injection attacks.
    Examples

    Example #1 Download dialog

    If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.



    Your headers now look like this:

    HTTP/1.1 200 OK
    Server: Apache/2.2.11 (Unix)
    X-Powered-By: PHP/5.2.8
    Date: Fri, 16 Oct 2009 23:05:07 GMT
    Connection: close

    16 years ago

    If you haven"t used, HTTP Response 204 can be very convenient. 204 tells the server to immediately terminate this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.

    Header("status: 204"); (or the other call)
    header("HTTP/1.0 204 No Response");

    10 years ago

    Here is a php script I wrote to stream a file and crypt it with a xor operation on the bytes and with a key:

    The encryption works very good but the speed is decrease by 2, it is now 520KiB/s. The user is now asked for a md5 password (instead of keeping it in the code directly). There is some part in French because it"s my native language so modify it as you want.



    2024 wisemotors.ru. How it works. Iron. Mining. Cryptocurrency.