Aug 19, 2022

Redirect IP Address to Domain Name in NGINX

Here's the instruction from Günter Scholtz on how to redirect IP address to domain name in Nginx and Apache.

Setting up a Default Route in Nginx

Method 1. Return a 301 redirect for requests made to IP.

server {
  listen 80;
  listen [::]:80;
  server_name 192.168.1.80;
 
  add_header X-Frame-Options "SAMEORIGIN";

  return 301 https://www.example.com$request_uri;
}

 Method 2. Return a 301 redirect which only no other rule matches. ('server_name _' means non-matches server name)

 server {
  listen 80 default_server;
  listen [::]:80 default_server;
  server_name _;

  return 301 https://www.example.com$request_uri;
}


Setting up a Default Route in Apache

Method 1. Redirect IP requests to domain name by adding a rewrite rule that matches the IP.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^192.168.1.80$
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Method 2. Redirect all other request (with no subdomains).

RewriteEngine on
RewriteCond %{SERVER_NAME} !=www.example.com
RewriteRule ^ https://www.example.com%{REQUEST_URI} [END,NE,R=301]


Links: