How to Create NGINX Redirects

October 6, 2023 / How-to Guide

This guide explains how to create NGINX redirects.

Follow the steps:

  1. Log in via SSH as the root user to access your NGINX web server.
  2. Utilise a text editor such as Nano, Vim, Emacs, or any of your preferences to modify the NGINX configuration file.
  3. We will make changes to the domain configuration files in the sites-enabled directory, which is the most straightforward way to implement NGINX redirects.
  4. These files may be named “default” or correspond to the specific domain you wish to configure.
    nano /etc/nginx/sites-enabled/default
    vim /etc/nginx/sites-enabled/
  5. Excluding the comments, the default file will have a structure similar to the code block provided below-
    server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;
    server_name _;
    location / {
    try_files $uri $uri/ =404;
  6. Many of the modifications mentioned below can be incorporated into the existing code. Please remember to restart NGINX after implementing these changes to ensure they are applied.
    systemctl restart nginx
  7. To save time on troubleshooting, it is a good practice to eliminate caching issues when testing your changes. You can do this by conducting your tests in a private browsing session.
  8. Redirect HTTP to HTTPS-To enforce encrypted connections, insert the following code on a new line below “server_name;”-
    return 301 https://$host$request_uri;
  9. Redirect to Force www-
    Opting for either the inclusion or exclusion of “www” in your website’s URL can enhance search engine optimization (SEO). Initially, place the following code above the current “server {” line:
    server {listen       80;server_name;}To enforce HTTPS, include this line before the closing } bracket.return 301$request_uri;Lastly, add the following to a new line under server_name _;-return 301$request_uri;
  10. Redirect a domain to another Domain-This is beneficial when transitioning your website to a new domain or subdomain (e.g., /blog or /forum). Insert the following code on a new line under “server_name _;”-return 301$request_uri;
  11. Permanent Redirect for a Single File-
    For redirecting a single page or file URL, place the following code on a new line below “server_name _;”-rewrite ^/page1.html$ /page2.html permanent;

This way you can create NGINX redirects. Hope you liked our article.

Spread the love