How to Write a Correct Nginx 301 Redirect

Redirecting HTTP to HTTPS uses Nginx redirect commands. So how should you write the redirect? Older versions of Nginx may have used formats similar to the following.

    rewrite ^/(.*)$ http://domain.com/$1 permanent;

    Or

    rewrite ^ http://domain.com$request_uri? permanent;

Now, newer versions of Nginx have adopted a different syntax, and the examples above are no longer recommended. You may still find many articles online using the first method, such as the author’s own post “How to Implement 301 Redirects in an LNMP Environment.”

Below is the latest recommended way to redirect HTTP pages to HTTPS in Nginx:

server {
       listen         80;
       server_name    my.domain.com;
       return         301 https://$server_name$request_uri;
}

server {
       listen         443 ssl;
       server_name    my.domain.com;

       [….]
}

Leave a Comment

Your email address will not be published.