How to create 301 redirect on Nginx & Apache

Sometimes we need to do a 301 redirect on the Apache or Nginx server to direct the old page to the new page, or to move to the preferred domain name.

Apache 301 redirect (on Linux/Unix servers)

Redirect 301 domain without www to domain with www
Add the following code into .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.url\.com$ [NC]
RewriteRule ^(.*)$ http://www.url.com/$1 [L,R=301]
Apache 301 redirect to a single url
RewriteEngine On
Redirect permanent /old-directory/old-file.html http://www.url.com/new-directory/new-file.html
Nginx 301 redirect
Add the following filter rules and rewrite rules to the corresponding Nginx configuration file:
server {
server_name www.A.com ;
rewrite ^(.*) http://www.B.com$1 permanent;
}

Not all the visits to station A are redirected to the specified page

server {
server_name www.A.com;
if ($host != ‘A.com’ ) {
rewrite ^/(.*)$ http://www.B.com/$1 permanent;
}
}