Nginx IP-to-Domain 301 Redirect Guide

# Nginx IP-to-Domain Redirect: Configure a 301 Redirect for Direct IP Access

A server can be reachable through its IP address even when the intended public address is a domain name. That can leave visitors at an address you do not want to promote and can split access between the IP and the canonical site URL. One straightforward Nginx approach is to make the default server return a permanent redirect to the HTTPS domain, while preserving the requested path and query string.

This guide explains the configuration shown in the source post: edit Nginx’s default site configuration, add separate HTTP and HTTPS default server blocks, point the HTTPS block at the domain certificate files, and restart Nginx after saving. The redirect uses a **301** status, which tells clients and search engines that the resource has moved permanently.

> **Risk and recency note:** Nginx configuration syntax, file layouts, certificate locations, and control commands can differ by operating system, package, and Nginx version. The configuration below is based on the source post. Review the active configuration and keep a backup before applying it; do not assume its paths or directives match every server.

## What this Nginx redirect does

The setup has one goal: when a request reaches the server through the server’s IP address, Nginx sends the visitor to `https://servername.com:443` and appends the original request URI.

For example, a request to an IP address with a path such as `/docs?page=2` is redirected to the equivalent location on the configured domain because the redirect target ends with `$request_uri`. That variable preserves the requested URI instead of sending every visitor only to the home page.

The source configuration covers both common entry points:

– **Port 80:** direct HTTP requests are redirected to the HTTPS domain.
– **Port 443:** direct HTTPS requests are also redirected to the HTTPS domain, using the configured TLS certificate and private-key files.

Using default server blocks is important in this pattern. A direct IP request may not match the site’s intended domain name, so Nginx needs a catch-all/default server that can handle it and return the redirect.

## Before editing the default Nginx site

Make a copy of the existing configuration before changing it. The source post identifies the file to edit as:

“`text
/etc/nginx/sites-available/default
“`

That path is common in some Nginx installations, but it is not universal. Confirm that this is the configuration file currently used by your server before modifying it.

You should also identify the domain you want to receive the redirected traffic. In the example, the placeholder is `servername.com`. Replace it consistently with the actual domain you intend visitors to use. The source configuration also references certificate files under:

“`text
/etc/letsencrypt/live/servername.com/
“`

Those certificate and key paths must correspond to the domain in the redirect. If the files are unavailable, inaccessible, or tied to a different name, the HTTPS default server may not behave as expected.

Keep the original configuration available for rollback. A small mistake in a server block, a certificate path, or a redirect target can affect how Nginx accepts requests.

## Edit the default Nginx configuration

Open `/etc/nginx/sites-available/default` and add the redirect logic shown below. Replace every instance of `servername.com` with the domain that should be canonical for your site.

“`nginx
server {
listen 80 default_server;
listen [::]:80 default_server;
return 301 https://servername.com:443$request_uri;
}

server {
listen 443 ssl default;
server_name _;
ssl_certificate /etc/letsencrypt/live/servername.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/servername.com/privkey.pem;
return 301 https://servername.com:443$request_uri;
}
“`

The first `server` block listens for HTTP traffic on port 80. It includes both an IPv4 listener and an IPv6 listener, then immediately returns the permanent redirect. There is no need for it to serve page content because its only job is to send the visitor to the selected HTTPS domain.

The second block handles the HTTPS side. It defines a catch-all `server_name _;`, supplies the certificate chain and private key paths from the source example, and returns the same redirect. This matters for direct HTTPS access: TLS is negotiated before Nginx can return an HTTPS redirect, so the block needs certificate settings.

The explicit `:443` in the redirect target is part of the source configuration. Keep it if you are following that configuration exactly. If your deployment uses a different port arrangement, do not change it casually; verify the intended public HTTPS endpoint first.

## Why `$request_uri` belongs in the redirect

The `$request_uri` variable is the part of the redirect that keeps the visitor’s requested location. Without it, a request for a specific path could be redirected only to the domain root, making the result less useful for visitors and potentially disrupting links to pages deeper in the site.

In this configuration, Nginx builds the destination by combining:

1. The HTTPS scheme: `https://`
2. The preferred domain: `servername.com`
3. The HTTPS port: `:443`
4. The original request URI: `$request_uri`

That produces a consistent destination on the domain while retaining the incoming path. It is the central behavior of the redirect rule.

## Save the file and restart Nginx

After saving the changes, restart the Nginx service as specified in the source post:

“`bash
systemctl restart nginx
“`

A restart applies the saved configuration. Because this is a server-level change, perform it with appropriate permissions and only after reviewing the file carefully.

If the service does not restart cleanly or the redirect does not work as expected, revert to the backup and check the active Nginx configuration, certificate locations, domain name, and permissions. Avoid repeatedly changing several variables at once; test one change at a time so the source of a problem is easier to isolate.

## Test the IP-to-domain redirect

Once Nginx has restarted, test direct access to the server IP address in a browser. Test both HTTP and HTTPS where your environment supports them. The expected behavior is a permanent redirect to the configured HTTPS domain.

Also test a non-home-page URL. The goal is not merely to see the domain in the browser bar; the original requested URI should remain present after the redirect because the rule uses `$request_uri`.

When checking results, look for these outcomes:

– A visit to the server IP over HTTP redirects to the HTTPS domain.
– A direct HTTPS visit reaches the HTTPS redirect server block and redirects to the domain.
– A requested path is retained after the redirect.
– The destination domain loads with the certificate files configured for that domain.

If any of these checks fail, stop and review rather than leaving a partially working redirect in production.

## Common configuration points to review

Most issues with this pattern come from environment differences rather than from the basic redirect statement. Start with the following details from the configuration:

### Confirm the actual Nginx site file

The example uses `/etc/nginx/sites-available/default`. Your server may organize Nginx sites differently. Ensure you are changing the file Nginx actually loads.

### Replace every placeholder domain

`servername.com` appears in the redirect URL and in both certificate paths. Leaving the placeholder in even one location creates an inconsistent configuration.

### Verify certificate and key paths

The HTTPS default server points to `fullchain.pem` and `privkey.pem` beneath `/etc/letsencrypt/live/servername.com/`. Those are the paths provided in the source post. Confirm that the relevant certificate material exists for your chosen domain before relying on direct HTTPS redirect behavior.

### Preserve the request URI

Do not omit `$request_uri` if your objective is to redirect individual URLs to their corresponding URLs on the domain. It is what carries the requested path through the redirect.

### Keep a rollback option

Configuration changes can have a wide effect because the default server handles unmatched requests. Retaining the pre-edit version makes recovery simpler if the server does not restart or requests route unexpectedly.

## Final takeaway

To redirect direct Nginx IP access to a canonical domain, configure default server blocks for port 80 and port 443 that return a 301 redirect to the HTTPS domain and append `$request_uri`. In the HTTPS block, use the certificate chain and private key for that domain. Then save the configuration and restart Nginx.

The technique is compact, but it is not a copy-and-forget change. Confirm the active Nginx file, replace the example domain and certificate paths accurately, preserve a backup, and test both the redirect and a specific URL after the restart. Those checks help ensure that direct IP traffic consistently lands on the intended domain without losing the requested path.