How to Set Up a 301 Redirect for Nginx?

Linode Staff

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 Redirectbeing 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:

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct