Score:0

Nginx IP to Domain Redirect

za flag

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;
Score:1
in flag

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.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.