Nginx IP to Domain Redirect

I've got a new server that redirects from all DNS requests to https to the domain name. I was having an issue with redirecting from the IP address and I added return 301 https://$host$request_uri; below.

Is return 301 https://$host$request_uri; the correct way to redirect from the IP to the domain?

server {
    if ($host = www.example.ext) {
        return 301 https://$host$request_uri;
    } 


    if ($host = example.ext) {
        return 301 https://$host$request_uri;
    } 


        listen 80 default_server;
        listen [::]:80 default_server;

        server_name example.ext www.example.ext;
        return 301 https://$host$request_uri;

There are four HTTP statuses that are generally used with redirections and a lot of developers tend to default to 301. While this will have the intended effect, it may not always be the best status code to use.

Here are the options:

Code Definition When to Use
301 Moved Permanently A domain or specific URL that once was valid has changed. The browser will cache this redirect and not look up the DNS routing again.
302 Found A URL is valid and has been temporarily moved elsewhere. The browser will cache the redirect for a short period (usually minutes) and retry if the URL is used again in the future.
307 Temporary Redirect A server is being built/rebuilt and, while the work is being done, visitors should be sent elsewhere. The browser will cache this redirect for a short period (usually minutes) and retry the DNS lookup later.
308 Permanent Redirect The requested resource may or may not have existed and traffic should be sent to a new location. The browser will cache this redirect and not look up the DNS routing again.

For your situation, a 301 is “adequate” but, if visitors were never supposed to interact with your server via the bare IP address, a 308 may be more accurate.

A short rule of thumb:

  • The URL used to be valid? Use 301/302.
  • The URL has never been valid? Use 307/308.