Any ucp php redirect. How to set a redirect to another URL in PHP before the page is loaded? HttpFox Add-on for Firefox

Quite an important point when setting up a site. An incorrectly configured redirect can severely damage the site's search results. The most common situations in which you have to use Permanent Redirect 301:

  • Website address change- you bought your domain and decided to move from site.example.com to site.ru
  • Gluing mirrors - if your site is available at www.site.ru and site.ru, search engines may consider it as two different sites, so first you need to decide on the main mirror (with www or without www) and set up redirects to the main mirror .
  • When a page (one or more) has changed its address- at some point it became clear that the addresses http://example.com/index.php?option=com_content&task=view&id=23&Itemid=1 are not good, and they need to be changed into http://example.com/sport/news12, but it's a pity to lose positions in the index of search engines (since this will be a new article for them).
  • Another way to deal with duplicate pages

Important: If the page has been moved temporarily, use 302 Moved Temporarily. Page merging in this case will not occur and the page with the redirect can always be restored.

Permanent Redirect 301 for apache (.htaccess)

You need to insert rules immediately after the lines:

RewriteEngine On RewriteBase / # to truncate the full path, from the server root to the site root

the rules themselves are set using regular expressions, recall the syntax:

  • Metacharacters, for specifying groups of characters or "labels" in a pattern:
    • ^ - line start mark,
    • $ - label end of line,
    • ! - denial,
    • \ - escaping slash, allows you to consider the following metacharacter as a regular character,
    • . - dot, denotes any character, but only one,
    • () - grouping.
  • Modifiers are placed after regular characters, metacharacters or their groups:
    • ? - the character is repeated 0 or 1 times,
    • * - repeats from 0 to 65536 times,
    • + - repeats from 1 to 65536 times.
  • Flags define additional options for this rule:
    • 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 can imagine, this is exactly what we need.
    • L - (last) stops the conversion process and the current link is considered final.

Consider the most common situations:

RewriteCond %(HTTP_HOST) ^www\.(.*) RewriteRule ^(.*)$ http://%1/$1 RewriteCond denotes a condition that, if matched, will execute the RewriteRule.

Redirect from index.php (html) to the main page

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

Redirect when changing the site structure

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

Permanent Redirect 301 in PHP

To tell the browser that it needs to redirect to the http://site.ru address from the page it requested, run the following commands:

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

Permanent Redirect 301 for nginx

Redirect rules are described in the server section.

Redirect from www.site.ru to site.ru

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

or general rule for all sites:

Server ( server_name ~^(?! www\.); rewrite ^ http://www.$host$request_uri permanent; )

Redirect from site.ru to www.site.ru

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

Redirect from index.php to the main page

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; )

The .htaccess configuration file is the config for Apache web servers. Most hosts work through this server, so this file is present on every site. Webmasters can partially manage its work by making their own changes to it. In this article, we will look at the directives and rules that can be changed in the server.

The most important .htaccess file is located at the root of the site:

Its actions apply to the current directory and all subdirectories. Those. site owners have the opportunity to influence only the work of their project, without interfering with the operation of the entire server. If this file is missing, then it can be created using any notepad. The main thing is that the file name should be ".htaccess" - without the formats .txt, .doc, etc.

Through the .htaccess file, 301 redirects are most often set up at the server level, which greatly speeds up the process of switching to new page, because no need to load intermediate page. It also specifies which file handles the 404 error.

A little lower, we will look at all common options for redirects through .htaccess , but first, let's get acquainted with the options and rules.

To be able to work with redirects, you need to enable the ReWriteEngine module. To do this, you need to write two lines of code (preferably at the very top of the .htaccess file):

Options +FollowSymLinks RewriteEngine On

Place these lines at the very top of your .htaccess file so that you can work with mod_write directives.

The hosting must also have mod_alias modules enabled (to support Redirect, RedirectPermanent and RedirectMatch).

1. Redirect, RewriteRule and RewriteCond rules

1.1. Redirect directive

Redirect syntax:

Redirect /from where http://where_full_address

Redirect sets up a direct redirect from one page to another.

In status write the redirect code. Is an optional parameter. Most often they write 301, which signals a permanent change in the address of the page.

It is important that the "from" page be written in the format without specifying full address site, but specifying the full relative URL starting with a slash "/" (i.e. from the root of the site). The page where the redirect goes should be written in full, i.e. the absolute address of the URL page (i.e. with the domain name and protocol http or https).

For example

Redirect 301 /oldpage.php http://site/newpage.php

You can also write differently

RedirectPermanent 301 /oldpage.php http://site/newpage.php or Redirect permanent 301 /oldpage.php http://site/newpage.php

1.2. RewriteRule Directive

The RewriteRule directive sets the transition rules. The syntax is the following:

RewriteRule Pattern Substitution [codes]
  • With an external redirect, the url of the address in the browser line changes - ""
  • With internal - does not change the url of the address in the browser line - " " or "[L] "

1.3. RewriteCond Directive

The RewriteCond directive defines the conditions under which the rules in the RewriteRule are executed.

RewriteCond Compare_String Condition

For example, these terms could be the user's browser, IP address, title, and so on.

1.4. RedirectMatch directive

The RedirectMatch directive is similar to Redirect, with the only difference that it allows you to write regular expressions.

RedirectMatch From Where To

2. Examples of 301 redirects in .htaccess

We have already covered many examples of .htaccess redirects in articles:

  • Change site address - redirect from the old domain to the new one

Here we will add options for redirects that have not yet been.

2.1. Redirect from one page to another

Redirect from site.ru/cat/oldpage to site.ru/newpage.html

RewriteRule ^cat/oldpage.* /newpage.html

Or the second option:

Redirect 301 /cat/oldpage http://www.site.com/newpage.php

2.2. Redirect from all .htm files to .html

RewriteCond %(REQUEST_FILENAME) !-f RewriteRule ^(.*)\.htm$ $1.html

Or the second option:

RewriteRule ^(.*)\.htm$ $1.html

2.3. Redirect entire directory to another page

Any page in the /old/ directory and subdirectories will be redirected to /new.php

RewriteRule ^old(.*)$ /new.php

2.4. Removing extra slashes in a URL

For example, the page /catalog///stranica.html is available and opens. To avoid such a situation and not produce an infinite number of duplicates, you should write the following redirect

RewriteCond %(REQUEST_URI) ^(.*)//(.*)$ RewriteRule . %1/%2

2.5. Rewrite without redirect

You can load another page without changing the page's URL. For example, let's load the page /news.html , and the address bar will display the address /news/happy

RewriteRule ^news/happy.* /news.html [L]

2.6. Putting a trailing slash at the end of the home page address

For example, many servers work so that the last slash is not written in the URL. For example, http://site.ru . The code below solves this problem: the site will open at http://site.ru/

RewriteCond %(REQUEST_URI) /+[^\.]+$ RewriteRule ^(.+[^/])$ %(REQUEST_URI)/

2.7. Removing a directory directory from a URL

For example, for a redirect from a page site.com/directoriya/page.html on site.com/page.html you need to write the following:

RewriteRule ^directoriya/(.+)$ http://site.com/$1

Or the second option:

RewriteCond %(DOCUMENT_ROOT)/directory/$1-f RewriteRule ^(.*)$ directory/$1

2.8. Redirect GET parameters

For example, redirect from the page /?act=page&id=2 to /page-2/

RewriteCond %(QUERY_STRING) act=page RewriteCond %(QUERY_STRING) id=(\d+) RewriteRule .* /page/%1/? ]

2.9. Redirect to the mobile version of the site m.site.ru

AT this example first, the fact that the user opened the site with mobile device(HTTP_USER_AGENT) , then the site address is replaced with m.URL

RewriteCond %(HTTP_HOST) ^(.*)$ RewriteCond %(HTTP_USER_AGENT) (?i:midp|samsung|nokia|j2me|avant|docomo|novarra|palmos|palmsource|opwv|chtml|pda|mmp|blackberry|mib|symbian|wireless|nokia|hand|mobi|phone|cdm|upb| audio|SIE|SEC|samsung|HTC|mot-|mitsu|sagem|sony|alcatel|lg|eric|vx|NEC|philips|mmm|xx|panasonic|sharp|wap|sch|rover|pocket|benq|java |pt|pg|vox|amoi|bird|compal|kg|voda|sany|kdd|dbt|sendo|sgh|gradi|jb|dddi|moto|iphone|android) RewriteRule ^$ http://m.%1

2.10. Redirect from subdomain

For example, let's redirect from any page of the subdomain poddomen.site.ru to the main domain site.ru

RewriteCond %(HTTP_HOST) ^poddomen.site.ru$ RewriteRule ^(.*)$ http://site.ru%(REQUEST_URI)

3.Other examples with htaccess

3.1. Deny IP address and browser

We will prohibit opening the site for a user from an IE browser with an IP address of 172.111.222.55

RewriteCond %(HTTP_USER_AGENT) MSIE RewriteCond %(REMOTE_ADDR) ^172\.111\.222\.55$ RewriteRule ^.*$ - [F]

3.2. Deny a specific file

Disable the file disable_file.html for everyone:

deny from all

3.3. Allow access from one ip

Access will be allowed only from one ip-address 172.111.222.55

order deny,allow deny from all allow from 172.111.222.55

3.4. Deny access from different ip

Deny access to the site from several IP addresses 172.112.222.55, 172.113.222.55, 172.114.*.*

order deny,allow deny from all deny from 172.112.222.55 deny from 172.113.222.55 deny 172.114.*.*

3.5. Redirect URL from big characters to small characters

All capital letters in the URL will be converted to small letters.

RewriteRule - RewriteRule ! - RewriteRule ^([^A]*)A(.*)$ $1a$2 RewriteRule ^([^B]*)B(.*)$ $1b$2 RewriteRule ^([^C]*)C(.* )$ $1c$2 RewriteRule ^([^D]*)D(.*)$ $1d$2 RewriteRule ^([^E]*)E(.*)$ $1e$2 RewriteRule ^([^F]*) F(.*)$ $1f$2 RewriteRule ^([^G]*)G(.*)$ $1g$2 RewriteRule ^([^H]*)H(.*)$ $1h$2 RewriteRule ^([^ I]*)I(.*)$ $1i$2 RewriteRule ^([^J]*)J(.*)$ $1j$2 RewriteRule ^([^K]*)K(.*)$ $1k$2 RewriteRule ^([^L]*)L(.*)$ $1l$2 RewriteRule ^([^M]*)M(.*)$ $1m$2 RewriteRule ^([^N]*)N(.*)$ $1n$2 RewriteRule ^([^O]*)O(.*)$ $1o$2 RewriteRule ^([^P]*)P(.*)$ $1p$2 RewriteRule ^([^Q]*)Q( .*)$ $1q$2 RewriteRule ^([^R]*)R(.*)$ $1r$2 RewriteRule ^([^S]*)S(.*)$ $1s$2 RewriteRule ^([^T] *)T(.*)$ $1t$2 RewriteRule ^([^U]*)U(.*)$ $1u$2 RewriteRule ^([^V]*)V(.*)$ $1v$2 RewriteRule ^( [^W]*)W(.*)$ $1w$2 RewriteRule ^([^X]*)X(.*)$ $1x$2 RewriteRule ^([^Y]*)Y(.*)$ $1y $2 RewriteRule ^([^Z]*)Z(.*)$ $1z$2 RewriteRule - [N] RewriteCond %(ENV:HASCAPS) TRUE Rewr iteRule ^/?(.*) /$1
45.4K

Anyone can send. But redirecting correctly is an art. But even more difficult is redirecting users to the right path on the Internet. The best way to do this is to redirect to php .

What is a redirect?

In web programming, there are situations when you need to redirect the user following the link to another address. Of course, at first glance, the implementation of 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, how to make a redirect;
  • When redrawing the structure of the resource, the addition, removal or transfer of entire sections or one material occurs. While this process is going on, you can temporarily 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 appear in the search results for some time. In this case, redirecting the user to new domain will be implemented search engine automatically;
  • In the authorization process - as a rule, on a large site 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 their rights and role. After authorization, the administrator or moderators of the site get into the administrative part of the resource, and visitors - to the user part of the resource.

Features of a redirect to php

Unlike others php languages has some advantages in implementing a redirect:

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

To redirect in php, use the header() function. 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– header line;

There are two types of this argument. The first 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 starts with "Location:"

  • bool $replace is an optional bool attribute. Responsible for overriding the previous header. If set to true , then 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 overwritten. The default is set to true ;
  • http_response_code - The argument forces the HTTP response code. Installation pass code succeeds, provided that the string argument is not empty.

The HTTP status code is part of the top line of the server response. The code consists of three digits followed by an explanatory inscription on English language. The first digit is responsible for the status class. Redirects correspond to codes from 300 to 307. Their full description can be found in the corresponding technical documentation.

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

Using the header() redirect

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

In another file, put the line:

echo "Hi! You are in redirect2.php";

A few more practical examples of using a redirect to php:

  • Forcing the http status code to be passed - when using the first argument of the header() function of the type " location» by default, the status code is sent to the header « 302 » ( temporarily moved). This can become a problem when transferring a resource to another domain name. In search engines, such a temporary redirect can be delayed. After all, the search engine constantly analyzes the status code. And it says " temporarily moved". An example of a forced rewrite of the status code " 302 " on the " 301 » ( permanently moved):

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

6.1K

Let's say you want users who visit a page to https://example.com/initial.php page https://example.com/final.php was displayed. This can be done with several PHP methods, JavaScript and HTML . In this article, we will cover each of the methods that you can use to redirect PHP to another page.

Here are a few variables we will be using:

Using the PHP header() Function to Redirect a URL

If you want to add a redirect from initial.php to final.php , you can put initial.php on the web page following code. It sends a new location header to the browser:

Here we are using PHP's header() function to create a redirect. You need to place this code before any HTML or text. Otherwise, you'll get an error that the header has already been sent. You can also use output buffering to avoid this error sending headers. In the following example this method PHP redirects shown in action:

To redirect using the header() function, the ob_start() function must come first in the PHP script. This will prevent header errors from occurring.

As an additional measure, you can add die() or exit() immediately after the header redirect so that the rest of the web page code is not executed. In some cases, crawlers or browsers may not pay attention to the indication in the Location header. What is fraught with potential threats to the security of the site:

To be clear: die() or exit() have nothing to do with redirects. They are used to prevent the rest of the code on the web page from executing.

When PHP redirects to a page, it is recommended to use absolute URLs when specifying the value of the Location header. But relative URLs will work too. You can also use this feature to redirect users to external sites or web pages.

Outputting JavaScript redirect code with PHP's echo() function

This is not a pure PHP solution. However, it is also effective. you can use PHP function echo() to output the JavaScript code that will handle the redirect.

If you use this solution, you won't have to use output buffering. This also prevents errors related to sending headers.

The following are some examples that use different JavaScript methods to redirect from the current page to another:

self.location="https://example.com/final.php";"; echo ""; echo ""; echo ""; ?>

The only downside to this method of redirecting to another PHP site is that JavaScript runs on the client side. And your visitors may have JavaScript disabled.

Using HTML meta tags for redirects

You can also use basic HTML to perform a redirect. It may sound unprofessional, but it works. And no need to worry about JavaScript being disabled in the browser or a headers error was previously sent:

You can also use the last line from the previous example to automatically refresh the page every " n» seconds. For example, the following code will automatically refresh the page every 8 seconds.

A computer