Common scenarios for using redirects in an Nginx configuration file

WebDev March 7, 2024
On this page
  1. Enforcing HTTPS (HTTP to HTTPS Redirects, redirect 80 to 443)
  2. Redirect traffic from the IP address directly to domain
  3. 404 Error Page Redirection
  4. Stupid problem with redirect while using Certbot

In Nginx configuration, redirects have a responsibility to inform the web server to display an HTTP status code on the client's screen, which is designing to tell the client that the asset is no longer available at its previous address. Primarily, the redirecting rules of Nginx work to optimize the users’ experience, secure and maintain a protected environment, and provide access to proper resources which will be discussed in detail.

Enforcing HTTPS (HTTP to HTTPS Redirects, redirect 80 to 443)

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

Redirect traffic from the IP address directly to domain

To redirect traffic from the IP address directly to your domain on port 443, you can create a separate server block for the IP address in your Nginx configuration:

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

The configuration for redirecting from port 443 to port 443 is the same for the IP address:

server {
    listen 443 ssl;
    server_name 11.111.111.111;
    return 301 https://example.com$request_uri;
}

However, this assumes that there's a specific reason for redirecting from port 443 to itself on the IP address, which is uncommon. Typically, redirection occurs from HTTP (port 80) to HTTPS (port 443).

404 Error Page Redirection

error_page 404 /custom-error-page.html;

Stupid problem with redirect while using Certbot

Sometimes, when using Certbot for getting ssl certificate, problems arise with redirection. For example, redirecting from 'http://www.example.com' to 'htttps://www.example.com' does not work. Therefore, it is very important to comment out the directives that the Certbot automatically writes in the file '/etc/nginx/sites-available/default'. Then the directives from the file '/etc/nginx/sites-available/your-site-config' will work correctly!