Server administration How to set up a 301 redirect

Underground Forum

Underground Forum

  • #1

301 redirect​


A 301 redirect is a permanent redirect from one page to another. Most often, webmasters use it when transferring a page to a new address, changing a domain name, or creating site mirrors.

Setting up a redirect via HTML and PHP​

Simple redirect:
<meta http-equiv="refresh" content="0;https://domain.com">
 <!-- content= --> delay in seconds (0 by default)

Each time, one of the 3 links will be used randomly:
<script type="text/javascript">

var urls=["https://link1/","https://link2/","https://link3/"];

document.write('<meta http-equiv="refresh" content="0;url='+urls[Math.round(Math.random()*(urls.length-1))]+'" />');

</script>

A simple redirect via PHP:
<?php

header(“HTTP/1.1 301 Moved Permanently”);

header(“Location: http://www.mysite.com/index.php”);

exit();

?>

Redirect via .htaccess (Apache)​

Redirect to another page:
RewriteCond %{REQUEST_URI} ^/contacts.html/$
RewriteRule ^.*$ https://domain.ru/contacts.html? [R=301,L]

Redirect to another domain:
RewriteEngine On
RewriteCond %{HTTP_HOST} domain-1.ru
RewriteRule (.*) https://domain-2.ru/$1 [R=301,L]

Redirect to https from http:
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

From www to domain:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.ru$ [NC]
RewriteRule ^(.*)$ http://domain.ru/$1 [R=301,L]

From domain to www:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^ domain.ru
RewriteRule (.*) http://www. domain.ru/$1 [R=301,L]

Redirect via NGINX​

From one address to another:
server {

  listen 443;

  location /forum/news {

   return 301 /threads/;

}

Redirect to https from http
server {
  listen 80;
  root /var/www/domain.ru/public;

  location / {
   return 301 https://domain.ru$request_uri;
  }
}

Redirect from www to domain:
server {

server_name www.[domain.ru];

return 301 $scheme://[domain.ru]$request_uri;

}
 
Top