====== Ubuntu - nginx - Redirects ======
===== Temporary Redirect =====
rewrite ^/oldlocation$ http://www.newdomain.com/newlocation redirect;
**Temporary redirects** (response status code 302 Found) are useful if a URL temporarily needs to be served from a different location. For example, if you are performing site maintenance, you may wish to use a temporary redirect of from your domain to an explanation page to inform your visitors that you will be back shortly.
----
Example:
server {
. . .
server_name www.domain1.com;
rewrite ^/$ http://www.domain2.com redirect;
. . .
}
This redirect instructs the browser to direct all requests for www.domain1.com to www.domain2.com.
This solution, however, works only for a single page, not for the entire site.
To redirect more than a single page, you can use the rewrite directive with regular expressions to specify entire directories instead of just single files.
**redirect** matches regular expression patterns in parenthesis. It then references the matched text in the redirect destination using $1 expression, where 1 is the first group of matched text. In more complex examples, subsequent matched groups are given numbers sequentially.
For example, if you wanted to temporarily redirect __every__ page within www.domain1.com to www.domain2.com, you could use the following:
server {
. . .
server_name www.domain1.com;
rewrite ^/(.*)$ http://www.domain2.com/$1 redirect;
. . .
}
server {
. . .
server_name www.domain2.com;
. . .
}
The **^/(.*)$** regular expression matches everything after the / in the URL.
For example, http://domain1.com/index.html will get redirected to http://domain2.com/index.html.
----
===== Permanent Redirect =====
rewrite ^/oldlocation$ http://www.newdomain.com/newlocation permanent;
**Permanent redirects** (response status code 301 Moved Permanently), on the other hand, inform the browser that it should forget the old address completely and not attempt to access it anymore. These are useful when your content has been permanently moved to a new location, like when you change domain names.
Multiple pages could be redirected if needed.
server {
. . .
server_name example.com www.example.com;
rewrite ^/products.html$ /offer.html permanent;
rewrite ^/services.html$ /offer.html permanent;
. . .
}