How to Set Up a 301 Redirect for Nginx?
I need to establish a 301 redirect from http to https.
3 Replies
Hey,
First I'd like to give a brief synopsis of what a 301 redirect is. We use 301 Moved Permanently
to reroute traffic from an old URL to a new one permanently. This differs from the 302 Temporary Redirect
being that the 302 is temporary.
You can implement a Permanent Redirect by adding the following syntax to your webserver configuration:
Permanent Redirects
rewrite ^/$ http://www.domain2.com permanent;
rewrite ^/(.*)$ http://www.domain2.com/$1 permanent;
You can implement a temporary redirect to your server configuration by using the example below:
Temporary redirect for a single page
server {
. . .
server_name www.domain1.com;
rewrite ^/(.*)$ http://www.domain2.com/$1 redirect;
. . .
}
server {
. . .
server_name www.domain2.com;
. . .
}
However, this solution only works for a single page, not for the entire site. If you want to redirect the entire website. Please use the following text as a template:
Temporary Redirect for an entire Website.
server {
. . .
server_name www.domain1.com;
rewrite ^/(.*)$ http://www.domain2.com/$1 redirect;
. . .
}
server {
. . .
server_name www.domain2.com;
. . .
}
Going forward with the method above all the traffic from http should reroute to https from now on.
I would recommend using the return
directive instead:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
access_log off;
error_log off;
return 301 https://$server_name$request_uri;
}
References: